Button that opens a new JFrame - java

I'm writing a program where I am supposed to have a title screen for a game, where you can click a 'play' button that opens a different window and simultaneously closes the other one. What I am attempting to do is utilize an ActionListener for a button that makes the current window invisible while simultaneously making a different window visible. I am having a hard time getting this to work and am encountering a lot of syntax and logical errors. I'm quite certain there is a better way to do this, so any pointers will be greatly appreciated. I am using swing. Disclaimer: beginner java level programmer lol :p
My first class includes this (does not include my imports):
public static void main(String[] args) {
//Creating the Frame
MyFrame menuFrame = new MyFrame();
// (here i have code for the frame in my actual program)
}
static class MyFrame extends JFrame {
MyFrame () {
this.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
this.getContentPane().add(new JLabel(new ImageIcon("logo.png")));
this.pack();
this.setVisible(true);
new EightOff.returnHomeListener (this);
}
}
}
My other class that has the other frame being opened includes the following button and action listener where I am trying to reference my frame from GameMenu:
public class EightOff
{
private static JButton returnHome = new JButton("Return to Game Menu");
public static class returnHomeListener implements ActionListener {
public returnHomeListener(GameMenu.MyFrame myFrame) {
}
#Override
public void actionPerformed(ActionEvent e)
{
returnHomeListener (JFrame visibleFrame) {
visibleFrame.toSetVisible (true);
}
}
}
}

You should start by having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener
The ActionListener should be registered to the button, so if can be notified when some action occurs, for example...
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JButton button = new JButton("Click me");
button.addActionListener(new TestActionListener());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "I'd prfefer if you did't do that");
}
}
}
In order to make changes to a object, you first need a reference to that object. This is pretty basic, Java 101 kind of stuff and you should have a look at Passing Information to a Method or a Constructor for more details.
You should also have a read of the JavaDocs for JFrame to get a better understanding of what properties and functionality the class provides.
Having a look at How to Make Frames also wouldn't hurt.
I'd recommend having a look at How to use CardLayout instead of trying to hide/show windows, you'll have a better user experience generally.

Related

how to define action listener for buttons in java

I have a jframe that includes JButton.I have six buttons in this frame, but I don't know how to define action listener for this buttons.please help to solve this problem.
First you have to import the package java.awt.event.* to enable events. After the class name you have to add implements ActionListener so that the class can handle events. When you have created the buttons you have to add an actionlistener to each button. Since you haven't showed which code you use I make an example with a simple program that counts votes, if the user clicks the yesButton the votes are increased with 1 and if the user clicks the noButton the votes are decreased with 1.
Here is the code to add an ActionListener to each button:
yesButton.addActionListener(this);
noButton.addActionListener(this);
Then write the following code to handle the events:
public void actionPerformed(ActionEvent e) {
JButton src = (JButton) e.getSource();
if(src.getActionCommand().equals("Yes")) {
yesCount++;
} else {
noCount++;
}
label.setText("Difference: " + (yesCount - noCount));
}
If you have 6 buttons you need to have an if statement and then 5 "else if" statements instead of only an if and an else statement.
Have a look at the Java tutorials on how to use ActionListeners:
https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html
Here's a simple example:
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.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Hello extends JPanel implements ActionListener {
JButton button;
public Hello() {
super(new BorderLayout());
button = new JButton("Say Hello");
button.setPreferredSize(new Dimension(180, 80));
add(button, BorderLayout.CENTER);
button.addActionListener(this); // This is how you add the listener
}
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e) {
System.out.println("Hello world!");
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Hello");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new Hello();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
buttons have a method called addActionListener, use that for adding the action listener that you can implement for the click...
Example:
dummyButton = new JButton("Click Me!"); // construct a JButton
add(dummyButton); // add the button to the JFrame
dummyButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(" TODO Auto-generated method stub");
}
});
It's really simple.
I suppose you have an instance of your button, right? Let's say that instance is called myButton.
You can just add an action listener by calling addActionListener:
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do whatever you like here
}
});
Protip: next time you don't know what method to call, just type the instance name and .. Then, your IDE will show you all the methods you can call, unless you are not using an IDE. If that is the case, download one.

JWindow not repainting until JFrame returns from while loop

Assume I have a JWindow and a JFrame called TestWindow and TestFrame which should both be shown at the same time, why does the TestWindow only draw a blank grey window without its label while the TestFrame is inside the while(true)???
And why if I remove the while(true) the TestWindow correctly shows?
This is as example of a more complex program where I need to show a splashscreen while the main application is starting which takes 1 or 2 seconds.
During this time the splashscreen should be shown regardless of the state of the main application, instead the splashscreen shows only when the main application is already finished, invokeAndWait doesn't actually wait for the splashscreen to be initialized.
TestFrame.java:
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class TestFrame extends JFrame
{
public static void main(String args[])
{
try
{
SwingUtilities.invokeAndWait(new Runnable()
{
#Override
public void run()
{
new TestWindow();
}
});
}
catch (Exception ex)
{
Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
}
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new TestFrame();
}
});
}
public TestFrame()
{
super("TestFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(new JLabel("sss"), BorderLayout.CENTER);
setSize(500, 120);
setVisible(true);
while(true)
{
//this makes the other not show
}
}
}
TestWindow.java:
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
public class TestWindow
{
public TestWindow()
{
JWindow jWindow = new JWindow();
JPanel contentPanel = new JPanel();
final JLabel label = new JLabel("Test Window");
contentPanel.add(label, BorderLayout.CENTER);
jWindow.add(contentPanel);
jWindow.setSize(300, 200);
jWindow.setAlwaysOnTop(true);
jWindow.setVisible(true);
}
}
EDIT:
By the way, I realized putting a
catch (Exception ex)
{
Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
Thread.sleep(1000);
}
between the two TestWindow and TestFrame creation actually solves the problem, isn't there anything less hacky than this???
Your while (true) loop is being called on the Swing event dispatch thread, or EDT, tying it up and preventing this thread from doing its necessary actions including drawing all your GUI's and interacting with the user. The solution is simple -- 1) get rid of the while loop (as you already figured out), or 2) if the loop is absolutely necessary, do it in a background thread.
For more details on Swing threading, please check out Lesson: Concurrency in Swing.

Java Swing. Opening a new JPanel from a JButton and making the buttons pretty

I am trying to build a little program that has a main GUI with 2 buttons. One button closes the program, the other I want to open a new JPanel that will have text fields etc.
I would like to be able to make the buttons so they look like normal application buttons I guess, nice and square, equal size etc. etc., I am not sure how to do this though.
Also, I am unsure how to open a new JFrame from a button click.
GUI Code:
package practice;
public class UserInterface extends JFrame {
private JButton openReportSelection = new JButton("Open new Window");
private JButton closeButton = new JButton("Close Program");
private JButton getCloseButton() {
return closeButton;
}
private JButton getOpenReportSelection() {
return openReportSelection;
}
public UserInterface() {
mainInterface();
}
private void mainInterface() {
setTitle("Program Information Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel(new GridLayout(0, 3));
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
getCloseButton().addActionListener(new Listener());
add(centerPanel, BorderLayout.CENTER);
setSize(1000, 200);
setVisible(true);
}
private void addReportPanel() {
JPanel reportPanel = createNewPanel();
getContentPane().add(reportPanel, BorderLayout.CENTER);
}
private JPanel createNewPanel() {
JPanel localJPanel = new JPanel();
localJPanel.setLayout(new FlowLayout());
return localJPanel;
}
}
ActionListener Class code:
package practice;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Listener implements ActionListener {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
}
EDIT: I think opening a new JPanel would be the way to go rather than a JFrame. What would be the best way to do this from a Jbutton click?
Start by using a different layout manager, FlowLayout or GridBagLayout might work better
JPanel centerPanel = new JPanel(new FlowLayout());
centerPanel.add(openReportSelection);
centerPanel.add(closeButton);
These layouts will honour the preferred sizes of your buttons
As for opening another window, well, you've already create one, so the process is pretty much the same. Having said that, you might consider having a look at The Use of Multiple JFrames: Good or Bad Practice? before you commit yourself to far.
A better approach might be to use a JMenuBar and JMenuItems to act as the "open" and "exit" actions. Take a look at How to Use Menus then you could use a CardLayout to switch between views instead, for example
From a pure design perspective (I know it's only practice, but perfect practice makes perfect), I wouldn't extend anything from JFrame and instead would rely on building your main GUIs around something like JPanel instead.
This affords you the flexibility to decide how to use these components, as you could add them to frames, applets or other components...
If you want your buttons to have the native Look and Feel (L&F), add the following to your program:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Instead of opening another JFrame, you'll want to instead use a JDialog, typically with modality set.
In Java, you can only extend one class and therefore you should consider carefully whether it is appropriate or not to extend another class. You could ask yourself, "Am I actually extending the functionality of JFrame?" If the answer is no, then you actually want to use an instance variable.
Below is an example program from the above recommendations:
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class MyApplication {
private JFrame myframe; // instance variable of a JFrame
private JDialog mydialog;
public MyApplication() {
super();
myframe = new JFrame(); // instantiation
myframe.setSize(new Dimension(400, 75));
myframe.getContentPane().setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JButton btnNewWindow = new JButton("Open New Window");
btnNewWindow.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
mydialog = new JDialog();
mydialog.setSize(new Dimension(400,100));
mydialog.setTitle("I got you! You can't click on your JFrame now!");
mydialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); // prevent user from doing something else
mydialog.setVisible(true);
}
});
myframe.getContentPane().add(btnNewWindow);
JButton btnCloseProgram = new JButton("Close Program :(");
btnCloseProgram.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myframe.dispose();
}
});
myframe.getContentPane().add(btnCloseProgram);
myframe.setVisible(true);
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
| UnsupportedLookAndFeelException e1) {
e1.printStackTrace();
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new MyApplication();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
I am not sure from your question what do wou want to do. Do you want to open a new JFrame or do you want to add a JPanel to the existing frame.
To open a new JFrame using a button, create an instance of the JFrame in the actionPerformed method of the button. In your case it would look similar to this:
openReportSelection.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFrame frame = new JFrame();
// Do something with the frame
}
}
});
You're probably looking up to create and open a new JFrame. For this purpose, first you need to instantiate an object from JFrame Class. As an example, Let's instantiate a new JFrame with specific boundries.
JFrame testFrame = new testFrame();
verificationFrame.setBounds(400, 100, 250, 250);
Then you need to create your components like JButtons, Jlabels and so on, and next you should add them to your new testFrame object.
for example, let's create a Jlabel and add it testFrame:
JLabel testLbl = new JLabel("Ok");
testLbl.setBounds(319, 49, 200, 30);
testFrame.getContentPane().add(testLbl);
Now let's suppose you have a Jbutton which is named "jbutton" and by clicking it, a new JFrame object will be created and the Jlabel component will be added to it:
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JFrame testFrame = new testFrame();
verificationFrame.setBounds(400, 100, 250, 250);
Label testLbl = new JLabel("Ok");
testLbl.setBounds(319, 49, 200, 30);
testFrame.getContentPane().add(testLbl);
}}});

How to make a start menu with another frame in Java?

So I'm making a game and It's working quite well, but I just need to have a start menu with 3 buttons. A Play, Instructions and Exit button. The problem is that I want it in a different frame than the game itself, if you press on Start the frame should switch to the game frame. Can someone help me with this?
This is a part of my code:
package frametest;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import javax.swing.*;
public class FrameTest extends JFrame implements ActionListener {
public JPanel createContentPane() {
//Jpanels and stuff
}
public JPanel createMainMenu() {
//Start menu JPanels and stuff
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Poker Game");
FrameTest demo = new FrameTest();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1080,640);
frame.setVisible(false);
JFrame menu = new JFrame("Poker Game");
menu.setContentPane(demo.createMainMenu());
menu.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menu.setSize(1080,640);
menu.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You must have a setting frame class for your main function and essential for frame and you should have another class for game controlling and a class for menu.
You should get instant of game controller in frame and do the same in controller for menu then you can have separate frame that you want.
please use interfaces to have a clean code.

Swing and events

Well, this is a very newie cuestion. Im stating to write by myself the code of my GUI applications with the help of window builder, i have decided to stop using netbeans couse ive read some peope in here that said that would be good. You may think i havent investigate, but trust me, i did my homework...
I tryed the way oracle says:
Declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example:
public class MyClass implements ActionListener {
Register an instance of the event handler class as a listener on one or more components. For example:
someComponent.addActionListener(instanceOfMyClass);
Include code that implements the methods in listener interface. For example:
public void actionPerformed(ActionEvent e) {
...//code that reacts to the action...
}
and my own way (wrong, off course, but i dont know whats wrong)
package Todos;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main extends JFrame {
private JPanel contentPane;
protected JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(new BorderLayout());
//setDefaultLookAndFeelDecorated(false);
//setIconImage(Image imagen);
setTitle("");
setSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
setPreferredSize(java.awt.Toolkit.getDefaultToolkit().getScreenSize());
setLocationRelativeTo(null);
this.btnNewButton = new JButton("New button");
this.btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
asd(arg0);
}
});
this.getContentPane().add(this.btnNewButton, BorderLayout.NORTH);
}
public void asd(ActionEvent arg0) {
this.getContentPane().add(new JButton("asd"));
}
}
The cuestion is, why this code doesnt work, the JButton im trying to add to the JFrame with the ActionPerformed event is not visible after i click.
This is an example code, may look silly, but i think it simplifies the cuestion, since my problem is in a few lines of code its not neccesary to show you the hole proyect.
Thank you in advance!
Your problem is here:
public void asd(ActionEvent arg0) {
this.getContentPane().add(new JButton("asd"));
}
Form Container.add() javadoc:
This method changes layout-related information, and therefore,
invalidates the component hierarchy. If the container has already been
displayed, the hierarchy must be validated thereafter in order to
display the added component.
You need to call validate() method to make added button visible:
public void asd(ActionEvent arg0) {
this.getContentPane().add(new JButton("asd"));
this.getContentPane().validate();
}

Categories

Resources