how to close a frame when button clicks

后端 未结 3 856
攒了一身酷
攒了一身酷 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.

    0 讨论(0)
  • 2021-01-24 09:42

    You can send a closing event to the frame/dialog. Like this:

    WindowEvent winClosingEvent = new WindowEvent( targetFrame, WindowEvent.WINDOW_CLOSING );
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
    

    I sometimes implement close() method in my frames/dialogs like this:

    public void close() {
        WindowEvent winClosingEvent = new WindowEvent( this, WindowEvent.WINDOW_CLOSING );
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
    }
    

    Hope that helped...

    0 讨论(0)
  • 2021-01-24 09:44

    Did you try calling dispose() on the frame? I think that may be what you're looking for.

    0 讨论(0)
提交回复
热议问题