I cannot close JFrame

348 views Asked by At

I have two java forms: NewJFrame i NewJFrame1. I have button on NewJFrame, so when I click on that button to open NewJFrame1 and close NewJFrame. It can open NewJFrame1, but it cannot close NewJFrame. This: NewJFrame frame = new NewJframe(); frame.setVisible(false); doesn't work. Also, frame.dispose(); doesnt work. CAn someone help me to soleve problem, how can I close NewJFrame by clicking on button in it (NewJFrame).

4

There are 4 answers

1
Jan On BEST ANSWER

In your code

NewJFrame frame = new NewJFrame();

creates a new (second) instance of NewJFrame. If you want to close the original one, you need a reference to this instance. Depending on your code, the reference could be this, so

this.dispose();

could work.

0
Nookie_IN On

Check if is frame visible before u trying to close it...Maybe u are trying to close wrong instance of frame... if u have NewJFrame frame = new NewJframe() then this same frame need to be closed .

frame.setVisible(false); or frame.dispose();

Just do dispose on original instance do not do JFrame frame = new JFrame()twice.

0
Puneet Chawla On

Try this one.. Hope, it will work.

       frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
1
jérémy Darchy On

I'm not really sure to understand why you are doing this, but I provided you a working sample :

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;


public class Tester implements ActionListener {
    private static final String SHOW = "show";
    private final JButton displayer = new JButton(SHOW);
    private final JButton hider = new JButton("hide");
    private final JFrame f;
    private final JFrame f1;

    Tester(){
        displayer.addActionListener(this);
        hider.addActionListener(this);

        f = new JFrame();
        f.setLayout(new FlowLayout());
        f.setSize(500, 500);
        f.add(displayer);
        f.add(hider);
        f.setVisible(true);

        f1 = new JFrame();
        f1.setSize(500, 500);
        f1.setLocationRelativeTo(null);
        f1.add(new JLabel("empty frame"));  
    }

    public static void main(String[] args) {
        new Tester();
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
            f1.setVisible(arg0.getActionCommand().equals(SHOW));
    }
}