Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a JFrame's close button click event?

I want to call a method confirmExit() when the red close button of the title bar of a JFrame is clicked.

How can I capture that event?

I'd also like to prevent the window from closing if the user chooses not to proceed.

like image 982
alxcyl Avatar asked Feb 01 '12 09:02

alxcyl


People also ask

How to close a JFrame when button clicks?

You can use super. dispose() method which is more similar to close operation. Show activity on this post. You cat use setVisible () method of JFrame (and set visibility to false ) or dispose () method which is more similar to close operation.

How do you make a JFrame close itself?

EXIT_ON_CLOSE (defined in JFrame) : Exit the application using the System exit method. Use this only in applications. might still be useful: You can use setVisible(false) on your JFrame if you want to display the same frame again. Otherwise call dispose() to remove all of the native screen resources.

What is setDefaultCloseOperation JFrame Exit_on_close?

Calling setDefaultCloseOperation(EXIT_ON_CLOSE) does exactly this. It causes the application to exit when the application receives a close window event from the operating system.


1 Answers

import javax.swing.JOptionPane; import javax.swing.JFrame;  /*Some piece of code*/ frame.addWindowListener(new java.awt.event.WindowAdapter() {     @Override     public void windowClosing(java.awt.event.WindowEvent windowEvent) {         if (JOptionPane.showConfirmDialog(frame,              "Are you sure you want to close this window?", "Close Window?",              JOptionPane.YES_NO_OPTION,             JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){             System.exit(0);         }     } }); 

If you also want to prevent the window from closing unless the user chooses 'Yes', you can add:

frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 
like image 195
Ravindra Gullapalli Avatar answered Oct 23 '22 02:10

Ravindra Gullapalli