in what way can this be programmed.
a UI box that displays random number between min and max value for 2 seconds then shows blank for 2 seconds then shows another random numer for 2 seconds then shows blank for 10 seonds and then repeats the cycle infitely until form closed. Font of the text to be configurable.
any help at all will be appreciated.
UPDATE after feedback
this is my progress so far. simple jpanel. now how do i add random number and timer
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RandomSlide {
public static void main(String[]args)
{
//Create a JPanel
JPanel panel=new JPanel();
//Create a JFrame that we will use to add the JPanel
JFrame frame=new JFrame("Create a JPanel");
//ADD JPanel INTO JFrame
frame.add(panel);
//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set JFrame size to :
//WIDTH : 400 pixels
//HEIGHT : 400 pixels
frame.setSize(400,400);
//Make JFrame visible. So we can see it
frame.setVisible(true);
}
}
You have multiple languages in your tags, so I'm unsure what to repond with.
For java you'd make a JPanel with the appropriate UI elements and build a Timer instance to shoot off scheduled events every 2 seconds to update the value.
In VBA for Excel you'd have to do the same with a Form and Timer Control, however you may encounter more issues in Excel/VBA than in java.
Update 16/04/2010
You can actually sub-class the JPanel to clean up the code.
class RandomDialog extends JFrame
{
private Timer _timer;
private JPanel _container;
public RandomDialog()
{
_timer = new Timer();
_container = new JPanel();
// Etc...
}
}
From here you can instantiate your children and register an event on the timer to call a function on your class which generates the random number and displays it to a JLabel.
Then you can just call your dialog in your driver like so:
public static void main(string [] args)
{
RandomDialog rand = new RandomDialog();
rand.show();
}
Here is some code that will get you rolling.
Note that you could just extend a JLabel instead of JPanel. I used JPanel based on your question. Also, note that you may use timer.setDelay() API to change the timing. Also, you could stop the timer by a stop() call.
package answer;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class RandomPanel extends JPanel implements ActionListener {
private static final int TWO_SECONDS=2000;
private static final int MAX=99999;
private static final int MIN=0;
private Timer timer = new javax.swing.Timer(TWO_SECONDS, this);
private JLabel msgLabel;
Random generator = new Random();
public RandomPanel(Font f){
msgLabel = new JLabel();
msgLabel.setFont(f);
msgLabel.setText(rand());
add(msgLabel);
}
#Override
public void actionPerformed(ActionEvent e) {
msgLabel.setText(msgLabel.getText().equals("")?rand():"");
}
private String rand() {
//generate random beteween MIN & MAX
return Integer.toString((int) (MIN + Math.random() * ( MAX - MIN) + 0.5));
}
public void start(){
timer.start();
}
/**
* Rudimentary test
* #param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
RandomPanel randomPanel = new RandomPanel(new Font("Serif", Font.BOLD, 50));
frame.getContentPane().add(randomPanel);
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
randomPanel.start();
}
}
Related
Hello first of all when I run the program a button appear , when I press the button the image will go from top to down.
I try the code when the image go from top to down , it work very well
BUT when I put all the codes together there is an error in ( frame.add(new AnimationPane() ); )
Question : How to add AnimationPane() to the frame ???
because this is my problem.
The idea that I want to make two scenes , the first one have a button to make go to the second scene which will have an image (it must be pushed from top until reach down ).
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package maincontentpaneswitching;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MainContentPaneSwitching {
private static class ChangeContentPaneListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// I want to put the image here
JPanel newFrameContents = new JPanel(); //Uses FlowLayout by default.
newFrameContents.add(new JLabel("You have successfully changed the content pane of the frame!", JLabel.CENTER));
/*We assume that the source is a JButton and that the Window is of type JFrame, hence
the following utility method call is possible without letting any errors appear:*/
JFrame frame = (JFrame) SwingUtilities.getWindowAncestor((JButton) e.getSource());
frame.setSize(600, 300);
frame.setContentPane(newFrameContents); //Change the content pane of the frame.
frame.revalidate(); //Notify the frame that the component hierarchy has changed.
frame.add(new AnimationPane() );
frame.pack(); //Resize the frame as necessary in order to fit as many contents as possible in the screen.
frame.setLocationRelativeTo(null); //Place the frame in the center of the screen. As you can tell, this needs its size to calculate the location, so we made sure in the previous line of code that it is set.
frame.repaint(); //Repaint frame with all its contents.
}
}
public class AnimationPane extends JPanel {
private BufferedImage boat;
private int yPos = 0;
private int direction = 1;
public AnimationPane() {
try {
boat = ImageIO.read(new URL("https://i.stack.imgur.com/memI0.png"));
Timer timer = new Timer(50, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
yPos += direction;
if (yPos + boat.getHeight() > getHeight()) {
yPos = getHeight() - boat.getHeight();
direction *= +1;
} else if (yPos < 0) {
yPos = 0;
direction *= +1;
}
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return boat == null ? super.getPreferredSize() : new Dimension(boat.getHeight()*2 , boat.getWidth() *2);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = getWidth() - boat.getWidth();
g.drawImage(boat, x, yPos, this);
}
}
private static class MainRunnable implements Runnable {
#Override
public void run() {
JButton changeContentPaneButton = new JButton("Click to go to the next image!");
changeContentPaneButton.addActionListener(new ChangeContentPaneListener());
JPanel frameContents = new JPanel(); //Uses FlowLayout by default.
frameContents.add(changeContentPaneButton);
JFrame frame = new JFrame("My application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tells the frame that when the user closes it, it must terminate the application.
frame.setContentPane(frameContents); //Add contents to the frame.
frame.pack(); //Resize the frame as necessary in order to fit as many contents as possible in the screen.
frame.setLocationRelativeTo(null); //Place the frame in the center of the screen. As you can tell, this needs its size to calculate the location, so we made sure in the previous line of code that it is set.
frame.setVisible(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new MainRunnable()); //Swing code must always be used in the Event Dispatch Thread.
}
}
Introduction
As I said in my comment, I couldn't get the image animation to work properly. At least this code would give you a solid foundation to start with.
Here's the GUI I came up with.
Here's the GUI after you left-click on the button.
If you're going to add comments to your code, put the comments on separate lines from the code. Not everyone has a large monitor and can read 200+ character lines of code.
Explanation
Oracle has a rad tutorial, Creating a GUI With Swing. Skip the Netbeans section.
When I create a Swing GUI, I use the model/view/controller (MVC) pattern. This pattern allows me to separate my concerns and focus on one part of the application at a time.
In Swing, the MVC pattern means:
The view reads information from the model
The view may not update the model
The controller updates the model and repaints/revalidates the view.
There's usually not one controller to "rule them all". Each listener controls its portion of the model and the view.
When I put together an application, I code one tiny tiny piece of it, then run tests. I probably ran two to three dozen tests, and this was mostly coded by you.
Model
I created a BoatImage class to read the boat image. It's a separate class, so I can read the image before I start to construct the GUI.
View
I created a JFrame. I created a main JPanel with a CardLayout.
I use a CardLayout to layout the button JPanel and the image JPanel. This way, the JFrame is not constantly changing size.
I create the JFrame and JPanels as separate methods/classes. This makes it much easier for people, including yourself, to read and understand the view code.
Controller
I coded the ChangeContentPaneListener to change from the button JPanel to the image JPanel. This is where you would put your image animation code.
Code
Here's the complete runnable code. I made all the additional classes inner classes so I could post this code as one block.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class MainContentPaneSwitching implements Runnable {
public static void main(String[] args) {
// Swing code must always be used in the Event Dispatch Thread.
SwingUtilities.invokeLater(new MainContentPaneSwitching());
}
private AnimationPane animationPane;
private BoatImage boatImage;
private CardLayout cardLayout;
private JPanel mainPanel;
public MainContentPaneSwitching() {
this.boatImage = new BoatImage();
}
#Override
public void run() {
JFrame frame = new JFrame("My application");
// Tells the frame that when the user closes it, it
// must terminate the application.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.mainPanel = createMainPanel();
frame.add(mainPanel, BorderLayout.CENTER);
// Resize the frame as necessary in order to fit as many contents
// as possible in the screen.
frame.pack();
// Place the frame in the center of the screen. As you can tell, this
// needs its size to calculate the location, so we made sure in the
// previous line of code that it is set.
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel createMainPanel() {
cardLayout = new CardLayout();
JPanel panel = new JPanel(cardLayout);
panel.add(createButtonPanel(), "button");
animationPane = new AnimationPane(boatImage);
panel.add(animationPane, "image");
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton changeContentPaneButton = new JButton(
"Click to go to the next image!");
changeContentPaneButton.addActionListener(
new ChangeContentPaneListener(this, boatImage));
panel.add(changeContentPaneButton);
return panel;
}
public JPanel getAnimationPane() {
return animationPane;
}
public void repaint() {
animationPane.repaint();
}
public class AnimationPane extends JPanel {
private static final long serialVersionUID = 1L;
private BoatImage boat;
public AnimationPane(BoatImage boat) {
this.boat = boat;
BufferedImage image = boat.getBoat();
this.setPreferredSize(new Dimension(image.getWidth(),
image.getHeight()));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
BufferedImage image = boat.getBoat();
int x = getWidth() - image.getWidth();
g.drawImage(image, x, boat.getyPos(), this);
}
}
private class ChangeContentPaneListener implements ActionListener {
private int direction, yPos;
private final MainContentPaneSwitching view;
private final BoatImage model;
public ChangeContentPaneListener(MainContentPaneSwitching view,
BoatImage model) {
this.view = view;
this.model = model;
this.direction = 1;
this.yPos = 0;
}
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(mainPanel, "image");
}
}
public class BoatImage {
private int yPos;
private BufferedImage boat;
public BoatImage() {
try {
URL url = new URL("https://i.stack.imgur.com/memI0.png");
boat = ImageIO.read(url); // boat.jpg
} catch (MalformedURLException e) {
e.printStackTrace();
boat = null;
} catch (IOException e) {
e.printStackTrace();
boat = null;
}
this.yPos = 0;
}
public BufferedImage getBoat() {
return boat;
}
public void setyPos(int yPos) {
this.yPos = yPos;
}
public int getyPos() {
return yPos;
}
}
}
I am programming a multiplication app for very large integers, I need to update every sigle step of the multiplication in a Swing component ( I created a JPane extended class with a JTextArea in it, then add it to the JFrame inside a ScrollPane). The issue is that this Swing component only updates once the multiplication algorithm is done. I tried using a Thread that would call repaint method of the Pane every 10 ms, but it did not work. The next is a sample of the problem.
This is the main Frame class:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Frame extends JFrame implements ActionListener{
private Console console;
private JButton calculate;
private Calculator calculator;
public Frame(){
console=new Console();
calculate=new JButton("Calculate");
calculate.addActionListener(this);
calculate.setActionCommand("");
calculator=new Calculator(this);
this.setLayout(new BorderLayout());
this.add(console,BorderLayout.CENTER);
this.add(calculate, BorderLayout.NORTH);
this.setTitle("Frame");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(new Dimension(500,500));
this.setLocationRelativeTo(null);
}
public void writeOnConsole(String txt){
console.write(txt);
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand().equals("")){
console.clear();
calculator.calculate();
}
}
public static void main(String[] args) {
new Frame();
}
}
This is the Console Class
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;
public class Console extends JPanel{
private JTextArea area;
public Console(){
this.setBorder(new TitledBorder("Console:"));
area=new JTextArea();
this.setLayout(new BorderLayout());
JScrollPane scroll=new JScrollPane(area);
this.add(scroll,BorderLayout.CENTER);
}
public void clear(){
area.setText("");
}
public void write(String txt){
area.append(txt+"\n");
}
}
Finally, this is the Calculator class (the one responsible for calling the writing)
public class Calculator {
private Frame parent;
public Calculator(Frame f){
parent=f;
}
public void calculate(){
for (int i = 0; i <= 1000000; i++) {
parent.writeOnConsole("Iteration "+i);
}
}
}
Note that if you run the program, the GUI will freeze until the Calculator class is done with the loop.
if you have a layout like a BorderLayout and you want to update it inside the JFrame do as bellow
JFrame frame = new JFrame();
BorderLayout layout = new BorderLayout();
layout.layoutContainer(frame.getContentPane());// use the frame as the border layout container
else you can use JFrame pack() method. The pack method packs the components within the window based on the component’s preferred sizes. it's not for updating but it updates the JFrame which is kind of a trick
JFrame frame = new JFrame();
//change the components dynamically
frame.pack();
or use Container methdod validate(). Validating a container means laying out its subcomponents. Layout-related changes, such as setting the bounds of a component, or adding a component to the container.
JFrame frame = new JFrame();
Container container = frame.getContentPane();
container.validate();
or if you want to update an specific component use
Component component = new JPanel();
component.repaint();
If this component is a lightweight component, repaint() method causes a call to this component's paint method as soon as possible .
or if you want for example numerous changes happen one by one dynamically then you could use the code below which is completely different from the things i said above. for that you could use platform.runlater() inside another thread which deals with everything that is about to change in realtime
new Thread(new Runnable()
{
#Override
public void run()
{
Platform.runLater(new Runnable()//use platform.runlater if you are using javafx
{
#Override
public void run()
{
try
{Thread.sleep(50);}catch(Exception e){}//use it in for loop where changes happen
//do some realtime change of components
}
});
}).start();
your Console class would be
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;
public class Console extends JPanel{
private JTextArea area;
public Console(){
this.setBorder(new TitledBorder("Console:"));
area=new JTextArea();
this.setLayout(new BorderLayout());
JScrollPane scroll=new JScrollPane(area);
this.add(scroll,BorderLayout.CENTER);
}
public void clear(){
area.setText("");
}
public void write(String txt){
area.append(txt+" "+"\n");
}
}
and the Calculator class is
public class Calculator {
private Frame parent;
public Calculator(Frame f){
parent=f;
}
public void calculate(){
new Thread(new Runnable() {
#Override
public void run()
{
for (int i = 0; i <= 100; i++) {
try
{
Thread.sleep(50);
}
catch(Exception e)
{
e.printStackTrace();
}
parent.writeOnConsole("Iteration "+i);
}
}
}).start();
}
}
as you can see i used another thread to do the changes
try the update method to call paint method for maintain every change
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm creating a "Snake" game as homework and I've passed hours searching around all the possible methods to close a JFrame, without conclusion. I started the program creating a JFrame with a background image and a menu, nothing more. When I click on the "Start game" button (JMenuItem) it opens a new JFrame with a thread to play the game. My problem is that the first JFrame doesn't close anyway I try to. I tried using these solutions and these and these but that JFrame's still there. It looks like the only command he listens to is the "EXIT_ON_CLOSE" as DefaultCloseOperation, not even the "DISPOSE_ON_CLOSE" is working. This is my SnakeFrame class:
package snake;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
/**
*
* #author Giacomo
*/
public class SnakeFrame extends Snake{
protected JMenuItem start = new JMenuItem("Start game");
public void pullThePlug(final SnakeFrame frame) {
/*// this will make sure WindowListener.windowClosing() et al. will be called.
WindowEvent wev = new WindowEvent(frame, WindowEvent.WINDOW_CLOSING);
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
// this will hide and dispose the frame, so that the application quits by
// itself if there is nothing else around.
frame.setVisible(false);
frame.dispose();*/
frame.addComponentListener(new ComponentAdapter() {
#Override
public void componentHidden(ComponentEvent e) {
((JFrame)(e.getComponent())).dispose();
}
});
}
public int game(final SnakeFrame frame,final JFrame gameFrame){
short game_ok=0;
try{
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
GameThread gamethread = new GameThread(frame,gameFrame);
gamethread.start();
pullThePlug(frame);
}
});
}
catch(Exception e){
game_ok=1;
}
return game_ok;
}
//-----------Frame initialization with relative Listeners and Events.---------\\
public SnakeFrame(){
JFrame frame= new JFrame("Le Snake");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double larghezza = screenSize.getWidth();
double altezza = screenSize.getHeight();
frame.setBounds(((int)larghezza/4),((int)altezza/4),800, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
ImageIcon icon = new ImageIcon("C:\\Users\\Giacomo\\Documents"
+ "\\NetBeansProjects\\Snake\\src\\res\\Snake-icon.png");
frame.setIconImage(icon.getImage());
frame.setResizable(false);
frame.setLayout(new GridLayout());
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
menuBar.setBounds(1, 1, frame.getWidth(),frame.getHeight()/25);
JMenuItem close = new JMenuItem("Exit");
close.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(start);
menu.add(close);
frame.setJMenuBar(menuBar);
try {
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read
(new File("C:\\Users\\Giacomo\\Documents\\NetBeansProjects\\"
+ "Snake\\src\\res\\default.png")))));
} catch (IOException e) {
System.out.println("Exception with the background image.");
}
frame.pack();
}
//-------------------------Frame initialization ended.-----------------------\\
}
Here's the game thread's code instead (for now):
package snake;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
/**
*
* #author Giacomo
*/
public class GameThread extends Thread implements Runnable{
private final SnakeFrame frame;
private final JFrame gameFrame;
public GameThread(final SnakeFrame f,final JFrame gF){
this.frame = f;
this.gameFrame = gF;
}
#Override
public void run(){
System.out.println("Game Thread started.");
final Label[][] griglia = new Label[50][50];
final Container container = new Container();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double larghezza = screenSize.getWidth();
double altezza = screenSize.getHeight();
gameFrame.setVisible(true);
gameFrame.setBounds(((int)larghezza/4),((int)altezza/4),
800, 600);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon("C:\\Users\\Giacomo\\Documents"
+ "\\NetBeansProjects\\Snake\\src\\res\\Snake-icon.png");
gameFrame.setIconImage(icon.getImage());
gameFrame.setResizable(false);
gameFrame.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e){
//Just to be sure he dies.
gameFrame.dispose();
frame.dispose();
System.exit(0);
}
});
gameFrame.setLayout(new GridLayout(50,50));
for(int i=0;i<50;i++){
for(int j=0;j<50;j++){
griglia[i][j] = new Label();
griglia[i][j].setBackground(Color.BLACK);
container.add(griglia[i][j]);
}
}
gameFrame.add(container);
}
}
Did I forget something? Does anyone have an idea? Sorry if my code's bad but I'm at school to learn :P I'm using NetBeans 8.0.2. Thanks everyone.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
EDIT:
I have now solved most of the problems I had, and here is the main:
public static void main(String[] args) {
final SnakeFrame frame = new SnakeFrame();
short isGameOk;
isGameOk =(short)frame.game(frame);
if(isGameOk==1)
System.err.println("Game Error!");
}
while here's the SnakeFrame class ("fixed"):
public class SnakeFrame extends Snake{
private final JMenuItem start = new JMenuItem("Start game");
private final BackgroundPanel defaultpanel;
public int game(final SnakeFrame frame){
short game_ok=0;
try{
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
defaultpanel.setVisible(false);
JPanel panel = new JPanel();
JLabel[][] griglia = new JLabel[50][50];
panel.setLayout(new GridLayout(50,50));
for(int i=0;i<50;i++){
for(int j=0;j<50;j++){
griglia[i][j] = new JLabel();
griglia[i][j].setBackground(Color.BLACK);
panel.add(griglia[i][j]);
}
}
frame.add(panel);
griglia[45][30].setIcon(new ImageIcon
("src\\res\\sneikhead.png"));
panel.setVisible(true);
}
});
}
catch(Exception e){
game_ok=1;
}
return game_ok;
}
//-----------Frame initialization with relative Listeners and Events.---------\\
public SnakeFrame(){
JFrame frame= new JFrame("Le Snake");
ImageIcon imm = new ImageIcon(getClass().getResource
("/res/default.png"));
Image background = imm.getImage();
defaultpanel = new BackgroundPanel(background, BackgroundPanel.ACTUAL,
1.0f, 0.5f);
frame.add(defaultpanel);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double larghezza = screenSize.getWidth();
double altezza = screenSize.getHeight();
frame.setBounds(((int)larghezza/4),((int)altezza/4),800, 600);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon imageIcon = new ImageIcon(getClass().getResource("/res/Snake-icon.png"));
Image icon = imageIcon.getImage();
frame.setIconImage(icon);
frame.setResizable(false);
frame.setLayout(new GridLayout());
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menuBar.add(menu);
menuBar.setBounds(1, 1, frame.getWidth(),frame.getHeight()/25);
JMenuItem close = new JMenuItem("Exit");
close.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menu.add(start);
menu.add(close);
frame.setJMenuBar(menuBar);
frame.pack();
}
//-------------------------Frame initialization ended.-----------------------\\
}
I am now able to change the SnakeFrame's background with a defaultpanel.setVisible(false); but the panel full of black colored labels that should show isn't visible even if I set it true. How can I get it visible? Thank you.
Some general comments:
Why are you creating a second frame? Usually a game is played in its own frame? You have a menu that allows you to change options of the game and this is done by display a modal JDialog. Then you have a "Start" button that starts the game by adding a panel to the existing frame.
Don't use a ComponentListener on the frame. There is no need to handle componentHidden.
Why do you have the game() method? I don't even see in your code where you invoke the method. Just add the actionListener to the Start menu item in the constructor of your class. Keep the creation of the menu item and the assignment of the actionListener in the same block of code so we don't need to look all over the class to find all the related properties for the component.
When I click on the "Start game" button (JMenuItem) it opens a new JFrame with a thread to play the game.
This is wrong. You should NOT be starting a separate Thread. All Swing components should be created on the Event Dispatch Thread (EDT). So basically the code should just be invoked from within your ActionListener since all event code does execute on the EDT.
It looks like the only command he listens to is the "EXIT_ON_CLOSE" as DefaultCloseOperation, not even the "DISPOSE_ON_CLOSE" is working.
Those are properties that you set for the frame. Then when the user clicks on the "X" button at the top/right of the frame the frame will close depending on the property. These properties have no effect when you invoke frame.dispose() or System.exit() directly.
GameThread gamethread = new GameThread(frame,gameFrame);
Why are you passing the frame to your other class? If you goal is to close the original frame. Then close the frame here after creating the other frame. In fact why do you even have a reference to the "gameFrame" here. If you have another class that creates the components of the frame, it should create the frame as well.
pullThePlug(frame);
This code does nothing. You are invoking this method AFTER you attempt to close the frame.
In general, I can't follow your logic since the code is not complete. However as a general rule an application should only contain a single JFrame. Hiding/showing multiple frames is not an experience uses want to see. When a new game starts you should just refresh the content pane of the existing frame.
I am working on a school assignment. We have 10 buttons, lets say first 10 letters of alpahabet. For exmaple when you click the 'A' button, character 'A' gets added to jLabel.
I know I could write new function for every button, but is there any better way? Like I pass the letter by argument and use only 1 function? Or is somehow possible to detect what button called my event handler and add letter according to that?
Yes, you can use actionCommand. Here you have examples doing that. How to use Buttons.
Example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ButtonExample {
private JPanel panel;
private JLabel label;
public ButtonExample(){
panel = new JPanel();
label = new JLabel(" ");
ActionListener listener = new MyActionListener();
JButton buttonA = new JButton("Press me A");
buttonA.setActionCommand("A");
buttonA.addActionListener(listener);
JButton buttonB = new JButton("Press me B");
buttonB.setActionCommand("B");
buttonB.addActionListener(listener);
JButton buttonC = new JButton("Press me C");
buttonC.setActionCommand("C");
buttonC.addActionListener(listener);
panel.add(buttonA);
panel.add(buttonB);
panel.add(buttonC);
}
private class MyActionListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
String text = (label.getText() == null || label.getText().isEmpty() )?"":label.getText();
label.setText(text+e.getActionCommand());
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Textfield example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationByPlatform(Boolean.TRUE);
ButtonExample buttonExample =new ButtonExample();
frame.add(buttonExample.panel,BorderLayout.CENTER);
frame.add(buttonExample.label,BorderLayout.NORTH);
//Display the window.
frame.pack();
frame.setVisible(Boolean.TRUE);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You can do like
Yourlabel.setText(yourbutton.getText());
It will place your button name say A to your desired label!
This is just a hint you can get an idea.
Im very new to java. I don't know what's wrong with my frame. I set the size to 300 and 200.
What Im seeing is a short and fat stick like thing.
Below is my code:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
public class BicycleDemo extends JFrame {
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = -4541236176053545919L;
public static void createGUI () {
JFrame jFrame = new JFrame("JFrame Demo");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container container = jFrame.getContentPane();
container.setLayout(new FlowLayout());
container.setBackground(Color.BLACK);
jFrame.setSize(300, 200);
jFrame.setResizable(false);
jFrame.pack();
jFrame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI ();
}
});
}
}
Please help.
You are calling pack(). pack() method resizes the frame to the smallest possible size to hold all the elements. So in fact you set the size to 200 x 300 and then resize the frame once more with pack().
Be aware however, that "hold all elements" is calculated by their preferred size, which can be just 0x0 pixels in a lot of cases.