How can I code a button that, when clicked, closes the current JFrame and opens a new one?
This is what I have so far, but the old frame stays open:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
practise1 s = new practise1();
s.setVisible(true);
}
I have tried using .close() after the first { but it gives me an error.
If you plan on using the originial JFrame later, use setVisible(false) on the original JFrame. If you plan on closing the first JFrame and never reusing it, you can use dispose().
public void actionPerformed(ActionEvent e)
{
if(e.getSource () == button)
{
test = new JFrame();
test.setSize(300,300);
test.setVisible (true);
this.dispose();
}
}
Dispose AFTER creating the new Frame.
Thanks for the help everyone. I got it working using the this.dispose(); method
Lets say current Frame is FirstFrame
and clicking on JButton goes to NewFrame
import javax.swing.*;
public class FirstFrame extends Jframe implements ActionListener{
JButton button;
public FirstFrame(){
setVisible(true);
setSize(500,500);
button=new JButton("Click me");
button.addActionListner(this);
add(button);
}
public static void main(String[] args)
{
new FirstFrame();
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
NewFrame nf=new NewFrame(); // Clicking on the Button will OPEN new Frame in NewFrame.java file
dispose(); //this method will close the FirstFrame
}
}
}
you just put this in your code :
(the exemple here i JButton to do this with the ActionPerformed method)
/**********************************************************************/
private void openBTNActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
FrameTarget t = new FrameTaregt();
t.setVisible(true);
//set the size : 1250 pixels de width and 720 pixels de height
t.setSize(1250, 720);
//make the frame in the center wuth this
t.setLocationRelativeTo(null);
t.setResizable(true);
}
Related
Having problems creating a custom JButton that is an Image. I had everything working with a normal JButton (like in the comment on the 2nd line) this way I wouldn't have to get an InputStream and start the button has an icon.
The trouble I'm having is that when I pressed the replay button (to play again) the window closes and only one window should pop out (as it happens with a "normal" JButton) but in this case 4-5 windows reopen and I don't know why.
I started thinking it was because the time to get an InputStream and doing ImageIO.read() the game would start and see that the variable running was false and then started reopening windows until it's true but I can't see how to verify that.
Note: I have functions that on ActionPerformed verify if the snake has collided and if so running = false and GameOver() will be called
public class GamePanel extends JPanel implements ActionListener {
JButton replay; //= new JButton("Play Again");
GamePanel() {
...
try {
InputStream is_replay = this.getClass().getResourceAsStream("/Snake/lib/img/playagain.png");
ImageIcon icon = new ImageIcon(ImageIO.read(is_replay));
replay = new JButton(icon);
replay.setBorder(BorderFactory.createEmptyBorder());
replay.setContentAreaFilled(false);
...
} catch (IOException|FontFormatException e) {
e.printStackTrace();
}
this.add(replay);
replay.setVisible(false);
replay.setBounds(SCREEN_WIDTH/2 - 100, SCREEN_HEIGHT - 200, 200, 100);
...
startGame();
}
public void startGame() {
spawnApple();
running = true;
timer = new Timer(DELAY, this);
timer.start();
}
public void gameOver(Graphics g) {
...
replay.setVisible(true);
replay.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == replay) {
JComponent comp = (JComponent)e.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose(); //It will close the current window
new GameFrame(); //It will create a new game
}
}
});
}
}
public class GameFrame extends JFrame {
GameFrame() {
JPanel panel = new GamePanel();
this.add(panel);
panel.setLayout(null); //Needed to add components
this.setTitle("Snake Game");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.pack(); //Fit JFrame to the components
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
public class SnakeGame {
public static void main(String[] args) throws Exception {
new GameFrame();
}
}
"in this case 4-5 windows reopen"
This suggests that you are probably adding multiple ActionListeners to the replay JButton. A new listener is added each time game over method is called, and this is incorrect. I would not add the ActionListener to the button in the game over method but rather add it once where you create the replay button.
Hi I created this java code for AWT Window
package labelExample;
import java.awt.*;
import java.awt.event.*;
public class labelExample extends Frame implements ActionListener{
Frame f;
TextField tf; Label l; Button b;
labelExample(){
Frame f=new Frame("Label Example");
tf=new TextField("www.google.de");
tf.setBounds(50,50, 150,20);
l=new Label();
l.setBounds(50,100, 250,20);
b=new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
f.dispose(); // use dispose method
}
}
);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new labelExample();
}
}
When I try to close the window by pushing the X button, nothing happens. The windows
stays open. I made these changes my example code:
public class labelExample extends Frame implements ActionListener{
I added new awt-frame f with name the "Label Example".
frame f;
frame f=new Frame("Label Example");
And added this code to close the frame
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
f.dispose(); // use dispose method
}
}
);
How do have change my code to fix this problem ?
I believe that in labelExample(){ ... } you should add a line setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); to close the window.
So I have this calculator when you first run it you will have to input name and section and then press submit and when you press submit 4 buttons will appear and each of those buttons will bring you to another JFrame. The problem is when I press back from that other JFrame it will direct me back from that main frame and you will again have to input name and section. How do I maintain the data which the user first inputted?
You can manage that using array of Jframes , when click frame you know the index of it
May be beacuse you are Extending JFrame. Which is a bad habit .
Here I have done a short EG which creates the Object of respective Frames and calls the method
setVisible(T/F) accordingly :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TestMultiFrames {
JFrame mainFrame,frame2,frame3;
public TestMultiFrames(){
mainFrame =new JFrame();
frame2 =new JFrame();
frame3 =new JFrame();
JPanel p=new JPanel();
JButton but1=new JButton("frame2");
JButton but2=new JButton("frame3");
JButton but3=new JButton("back to frame 3");
p.add(but1);
frame2.add(but2);
frame3.add(but3);
but1.addActionListener(new CustomActionListener1());
but2.addActionListener(new CustomActionListener2());
but3.addActionListener(new CustomActionListener3());
mainFrame.add(p);
mainFrame.setSize(200,200);
frame2.setSize(200,200);
frame3.setSize(200,200);
mainFrame.setVisible(true);
}
public static void main(String... args)
{
new TestMultiFrames ();
}
class CustomActionListener1 implements ActionListener{
public void actionPerformed(ActionEvent e) {
mainFrame.setVisible(false);
frame2.setVisible(true);
}
}
class CustomActionListener2 implements ActionListener{
public void actionPerformed(ActionEvent e) {
frame2.setVisible(false);
frame3.setVisible(true);
}
}
class CustomActionListener3 implements ActionListener{
public void actionPerformed(ActionEvent e) {
frame3.setVisible(false);
frame2.setVisible(true);
}
}
}
I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?
Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
See How to Write an Action Listener.
I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.
Hope this helps
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});
Could you please help me on this one? I have a JDialog with some textfields, checkboxes and buttons. I want that when the frame is not focused anymore, to disappear. So I added a focus listener to the JDialog and when the focus is lost, I call dialog.setVisible(false);. The problem is that if I click on the checkbox,textfield or button, the frame loses it's focus and disappears. How could I keep it focused until the user clicks outside it's area?
EDIT : The "frame" I am referring to is a JDialog. I don't use a Frame nor a JFrame. All the components are placed on the JDialog. I want it to hide when not focused, but keep it focused until the user clicks outside it's area.
Seems like you had added the wrong Listener, what you should be adding is addWindowFocusListener(...), see this small sample program, is this what you want to happen :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DialogFocus
{
private JFrame frame;
private MyDialog myDialog;
public DialogFocus()
{
}
private void createAndDisplayGUI()
{
frame = new JFrame("JFRAME");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
myDialog = new MyDialog(frame, "My Dialog", false);
JButton showButton = new JButton("SHOW DIALOG");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (!(myDialog.isShowing()))
myDialog.setVisible(true);
}
});
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String\u005B\u005D args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DialogFocus().createAndDisplayGUI();
}
});
}
}
class MyDialog extends JDialog
{
private WindowFocusListener windowFocusListener;
public MyDialog(JFrame frame, String title, boolean isModal)
{
setTitle(title);
setModal(isModal);
JPanel contentPane = new JPanel();
JTextField tfield = new JTextField(10);
JComboBox cbox = new JComboBox();
cbox.addItem("One");
cbox.addItem("Two");
cbox.addItem("Three");
contentPane.add(tfield);
contentPane.add(cbox);
windowFocusListener = new WindowFocusListener()
{
public void windowGainedFocus(WindowEvent we)
{
}
public void windowLostFocus(WindowEvent we)
{
setVisible(false);
}
};
addWindowFocusListener(windowFocusListener);
add(contentPane);
pack();
}
}
Make the dialog modal, then the user cannot click on the frame.
Check the FocusEvent
it has public Component getOppositeComponent(). If the opposite component is child component of the JDialog don't hide the dialog.