How to programmatically close a JFrame

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

    If you really do not want your application to terminate when a JFrame is closed then,

    use : setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    instead of : setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Here's a synopsis of what the solution looks like,

     myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
    
    0 讨论(0)
  • 2020-11-22 06:26

    This answer was given by Alex and I would like to recommend it. It worked for me and another thing it's straightforward and so simple.

    setVisible(false); //you can't see me!
    dispose(); //Destroy the JFrame object
    
    0 讨论(0)
  • 2020-11-22 06:28

    I have tried this, write your own code for formWindowClosing() event.

     private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
        int selectedOption = JOptionPane.showConfirmDialog(null,
                "Do you want to exit?",
                "FrameToClose",
                JOptionPane.YES_NO_OPTION);
        if (selectedOption == JOptionPane.YES_OPTION) {
            setVisible(false);
            dispose();
        } else {
            setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        }
    }    
    

    This asks user whether he want to exit the Frame or Application.

    0 讨论(0)
  • 2020-11-22 06:30

    Based on the answers already provided here, this is the way I implemented it:

    JFrame frame= new JFrame()
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    // frame stuffs here ...
    
    frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
    

    The JFrame gets the event to close and upon closing, exits.

    0 讨论(0)
  • 2020-11-22 06:35

    Here would be your options:

    System.exit(0); // stop program
    frame.dispose(); // close window
    frame.setVisible(false); // hide window
    
    0 讨论(0)
  • 2020-11-22 06:38

    Not only to close the JFrame but also to trigger WindowListener events, try this:

    myFrame.dispatchEvent(new WindowEvent(myFrame, WindowEvent.WINDOW_CLOSING));
    
    0 讨论(0)
提交回复
热议问题