Search code examples
javaswingjframedispose

Default Close Operation of a JFrame isn't working


I'm using NetBeans. My JFrame has as default close operation: EXIT_ON_CLOSE. I have a button that is supposed to close the program on this JFrame, this is the action performed code:

private void bSalirActionPerformed(java.awt.event.ActionEvent evt){                                       
    this.dispose();
}  

I thought this would close all the JFrames of the program but it doesn't, could you explain me why or how to fix it?


Solution

  • If you want to exit your application with the button than you can use System.exit() or frame.dispose().

    but be careful with System.exit() as this will terminate the JVM.

    So it is better to first confirm from user before this. with JOptionPane.showConfirmDialog();

    private void bSalirActionPerformed(java.awt.event.ActionEvent evt){ 
    
            int exit = JOptionPane.showConfirmDialog(
                    frame,
                    "Are you sure you want to exit the application?",
                    "Exit Application",
                    JOptionPane.YES_NO_OPTION);                             
            if(JOptionPane.YES_OPTION == exit){
                 frame.dispose(); // or System.exit(1);
            }
        }