How to programmatically close a JFrame

前端 未结 17 1180
深忆病人
深忆病人 2020-11-22 05:42

What\'s the correct way to get a JFrame to close, the same as if the user had hit the X close button, or pressed Alt+F4 (on W

17条回答
  •  余生分开走
    2020-11-22 06:39

    Best way to close a Swing frame programmatically is to make it behave like it would when the "X" button is pressed. To do that you will need to implement WindowAdapter that suits your needs and set frame's default close operation to do nothing (DO_NOTHING_ON_CLOSE).

    Initialize your frame like this:

    private WindowAdapter windowAdapter = null;
    
    private void initFrame() {
    
        this.windowAdapter = new WindowAdapter() {
            // WINDOW_CLOSING event handler
            @Override
            public void windowClosing(WindowEvent e) {
                super.windowClosing(e);
                // You can still stop closing if you want to
                int res = JOptionPane.showConfirmDialog(ClosableFrame.this, "Are you sure you want to close?", "Close?", JOptionPane.YES_NO_OPTION);
                if ( res == 0 ) {
                    // dispose method issues the WINDOW_CLOSED event
                    ClosableFrame.this.dispose();
                }
            }
    
            // WINDOW_CLOSED event handler
            @Override
            public void windowClosed(WindowEvent e) {
                super.windowClosed(e);
                // Close application if you want to with System.exit(0)
                // but don't forget to dispose of all resources 
                // like child frames, threads, ...
                // System.exit(0);
            }
        };
    
        // when you press "X" the WINDOW_CLOSING event is called but that is it
        // nothing else happens
        this.setDefaultCloseOperation(ClosableFrame.DO_NOTHING_ON_CLOSE);
        // don't forget this
        this.addWindowListener(this.windowAdapter);
    }
    

    You can close the frame programmatically by sending it the WINDOW_CLOSING event, like this:

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

    This will close the frame like the "X" button was pressed.

提交回复
热议问题