how to close a frame when button clicks

后端 未结 3 857
攒了一身酷
攒了一身酷 2021-01-24 08:52

I am new to Java Swing. I am creating a frame with some components.

I have to close the frame and open another frame when the button is clicked. I had tried setVis

3条回答
  •  别那么骄傲
    2021-01-24 09:32

    looking at your code, you'll probably need something like this:

                if(frame == null)
                    frame = new JFrame();
                else {
                    //remove the previous JFrame
                    frame.setVisible(false);
                    frame.dispose();
                    //create a new one
                    frame = new JFrame();
                }
    

    you'll have to put this inside the actionperformed method so that the frame can be removed.. btw, it would be a gd idea to change your class variables from public to private, in accordance with good programming practice..

    EDIT: To answer the "flickering" problem. you're accessing the swing component from outside the event thread. swing widgets arent generally thread safe. as such, u need to modify your main method:

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                designUI();
            }
        });
    }
    

    also, refer to Swing component flickering when updated a lot for further queries.

提交回复
热议问题