I am building a text editor and I don't know how to handle a listener on Swing exit button, which is create automatically. I want to use dialogs when user doesn't save file, for example press exit button.
Asked
Active
Viewed 53 times
0
-
Welcome to SO. What does it mean created automatically ? By GUI builder ? So use the GUI builder to add a listener. If it has a listeners - edit it. If it doesn't and you can't add one - you can't use it. – c0der May 13 '17 at 08:25
-
2Maybe he means the window decorations provided by Windows, Mac OS, or whatever operating system? – Kevin Anderson May 13 '17 at 09:03
-
It is not clear what kind of exit-button you mean. You should add a screen-shot showing it. – Thomas Fritsch May 13 '17 at 10:23
3 Answers
1
final JFrame f = new JFrame("Good Location & Size");
// make sure the exit operation is correct.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent we) {
// pop the dialog here, and if the user agrees..
System.exit(0);
}
});
As seen in this answer to Best practice for setting JFrame locations, which serializes the frame location & size before exiting.

Community
- 1
- 1

Andrew Thompson
- 168,117
- 40
- 217
- 433
0
Go stepwise:
- Declare a boolean variable
saved
and set its default value to false. - When user saves the file, change it to true
- When exit button is pressed, check the variable.
- If
true
, exit, else, prompt user for saving file.
So, finally this code snippet looks like:
public boolean saved = false;
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
saved = true;
//Code to save file
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(saved)
System.exit(0);
else {
//Code to prompt user to save file
}
}
});

Deepesh Choudhary
- 660
- 1
- 8
- 17
-
i cant add listener to exit button because this button is creating automatically – sadasdaaaa May 13 '17 at 08:16
-
1@thenewproblem add all important info to the question. Not in comments. What does it mean created automatically ? If it has a listeners - edit it. If it doesn't and you can't add one - you can't use it. – c0der May 13 '17 at 08:24
0
Assuming you have a handle on your window, assuming it's a Window
object (e.g. a JFrame
or other kind of window), you can listen to WindowEvent
events. Here is an example with windowClosed
, you can replace it with windowClosing
if you need to intercept it before.
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent e) {
// do something here
}
});

Hugues M.
- 19,846
- 6
- 37
- 65