How to programmatically close a JFrame

前端 未结 17 963
深忆病人
深忆病人 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:20

    This examples shows how to realize the confirmed window close operation.

    The window has a Window adapter which switches the default close operation to EXIT_ON_CLOSEor DO_NOTHING_ON_CLOSE dependent on your answer in the OptionDialog.

    The method closeWindow of the ConfirmedCloseWindow fires a close window event and can be used anywhere i.e. as an action of an menu item

    public class WindowConfirmedCloseAdapter extends WindowAdapter {
    
        public void windowClosing(WindowEvent e) {
    
            Object options[] = {"Yes", "No"};
    
            int close = JOptionPane.showOptionDialog(e.getComponent(),
                    "Really want to close this application?\n", "Attention",
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.INFORMATION_MESSAGE,
                    null,
                    options,
                    null);
    
            if(close == JOptionPane.YES_OPTION) {
               ((JFrame)e.getSource()).setDefaultCloseOperation(
                       JFrame.EXIT_ON_CLOSE);
            } else {
               ((JFrame)e.getSource()).setDefaultCloseOperation(
                       JFrame.DO_NOTHING_ON_CLOSE);
            }
        }
    }
    
    public class ConfirmedCloseWindow extends JFrame {
    
        public ConfirmedCloseWindow() {
    
            addWindowListener(new WindowConfirmedCloseAdapter());
        }
    
        private void closeWindow() {
            processWindowEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
        }
    }
    

提交回复
热议问题