简体   繁体   中英

How can I open a frame and close the old one with a button?

I have 2 frames. Frame1 list a table with data. Frame2 puts new data to table. And a button opens Frame2 . In Frame2 , I write the things to put the table and write them to a txt file. And in Frame1 , I put items from a txt file to the table.

However, when I go back to the Frame1 , it is still the old table. Because I have not reset it. Because it gets items when it opens and it opens before Frame2 . So I want to close Frame1 when I click the button and open Frame2 . And after I am done with Frame2 , I want to go back to Frame1 . So Frame1 can be the new table.

Here is what I wrote but when I click the button Frame1 does not close:

btnNewButton.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent e) {
        
        try {
            Frm1 frm1 = new Frm1();//using try / catch becouse of files.
            Frm2 frm2 = new Frm2();
            frm1.setVisible(false);// i made it as frm2 first and frm1 after and nothing changed.
            frm2.setVisible(true);
            
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        
    }
});

Note:

Frm1 frm1 = new Frm1();

I tried to take this code out of the event. But I get error:

Exception in thread "AWT-EventQueue-0"

I guess it is because of I already have it in ( public static void main(String[] args) ).

frm1.dispose();

And tried this too. Is it not working.

Frame1 Code
Frame2 Code
Fonks Code

You are creating an Frm1 and Frm2 object each time you click that button. So you are basicly not hiding your original Frm instead you hide the new one. A simple idea to fix this issue would be to initialize both frames in an upper laying class like an controller class and just to set the visibilty of the Frm2 object to false. In the mouseClicked you can just swap the booleans from both frames then by using a global variable of them.

If my answer doesn't help please provide more code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM