Do something when the close button is pressed on the JFrame

Is there a way to somehow "do something" when I click the red close button in the JFrame title bar? What I want to do is call a method called confirmExit() when this button is clicked. So far, the only option I have is to get him to do nothing, but I don’t want to. How to do it?

Thanks in advance.

+61
java swing jframe windowlistener
Feb 01 2018-12-12T00:
source share
6 answers
 import javax.swing.JOptionPane; import javax.swing.JFrame; /*Some piece of code*/ frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { if (JOptionPane.showConfirmDialog(frame, "Are you sure to close this window?", "Really Closing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){ System.exit(0); } } }); 
+102
Feb 01 2018-12-12T00:
source share

Override the window closing method.

 public void windowClosing(WindowEvent e) 

It is called when the window is in the process of closing. At this point, the close operation can be overridden.

+24
Feb 01 2018-12-12T00:
source share
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

also works. First create a JFrame called a frame, then add this code below it.

+5
Feb 01 '12 at 9:33
source share

This is what I put as a menu option, where I made a button on a JFrame to display another JFrame . I wanted only the new frame to be visible, and not to destroy the one behind it. At first I hid the first JFrame , and the new one became visible. After closing the new JFrame I deleted it and then repeated the old one.

Note. The following code extends Ravinda's answer, and ng 's JButton :

 ng.addActionListener((ActionEvent e) -> { setVisible(false); JFrame j = new JFrame("NAME"); j.setVisible(true); j.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { setVisible(true); } }); }); 
+1
Nov 20 '17 at 21:20
source share

Try the following:

 setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); 

He will work.

0
Apr 18 '16 at 12:26
source share

This may work:

 jdialog.addWindowListener(new WindowAdapter() { public void windowClosed(WindowEvent e) { System.out.println("jdialog window closed event received"); } public void windowClosing(WindowEvent e) { System.out.println("jdialog window closing event received"); } }); 

Source: https://alvinalexander.com/java/jdialog-close-closing-event

0
04 Sep '17 at 15:31 on
source share



All Articles