Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close to JFrame window

Tags:

java

swing

jframe

I have a JFrame which I want to press the "X" key (close the JFrame) to confirm if I really want to close the application or not. If I click "NO", it closes the application.

Why doesn't it work if I select "NO"?

    setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    addWindowListener(new java.awt.event.WindowAdapter() {
        @Override
        public void windowClosing(java.awt.event.WindowEvent evt){
            if (JOptionPane.showConfirmDialog(rootPane, "Confirm out?", 
                    "AppLocal", JOptionPane.ERROR_MESSAGE) == JOptionPane.ERROR_MESSAGE){
                dispose();
            }
        }
    });

enter image description here

enter image description here

like image 524
SrCantabri Avatar asked Mar 08 '26 16:03

SrCantabri


1 Answers

Method:
int javax.swing.JOptionPane.showConfirmDialog(Component parentComponent, Object message, String title, int optionType) throws HeadlessException

In optionType parameter, you have to use:

  • JOptionPane.YES_NO_OPTION
  • JOptionPane.YES_NO_CANCEL_OPTION
  • JOptionPane.OK_CANCEL_OPTION

The available return values are:

    //
    // Return values.
    //
    /** Return value from class method if YES is chosen. */
    public static final int         YES_OPTION = 0;
    /** Return value from class method if NO is chosen. */
    public static final int         NO_OPTION = 1;
    /** Return value from class method if CANCEL is chosen. */
    public static final int         CANCEL_OPTION = 2;
    /** Return value form class method if OK is chosen. */
    public static final int         OK_OPTION = 0;
    /** Return value from class method if user closes window without selecting
     * anything, more than likely this should be treated as either a
     * <code>CANCEL_OPTION</code> or <code>NO_OPTION</code>. */
    public static final int         CLOSED_OPTION = -1;

So, your code can be:

setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new java.awt.event.WindowAdapter() {
    @Override
    public void windowClosing(java.awt.event.WindowEvent evt) {
        if (JOptionPane.showConfirmDialog(rootPane, "Confirm out?", 
            "AppLocal", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION
        ) {
            dispose();
        }
    }
});
like image 123
Stéphane Millien Avatar answered Mar 11 '26 05:03

Stéphane Millien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!