How can I set an action command to window closing event?

3.3k Views Asked by At

How can I set an action command to closing event of a custom frame class which is a subclass of javax.swing.JFrame?

This is the current code:

this.addWindowListener(new WindowAdapter() {
  @Override
  public void windowClosing(WindowEvent e) {
    // some stuff here
  }
});

The code that goes in // some stuff here is shared with a button labeled quit. For the button, I have set an action command to "quit" and set the listener to an external class named NavigationHandler whose actionPerformed has a case for "quit". If I could set the action command of my window closing event to "quit", I could use the same listener for the window too.

Currently I have a method that I call from both sites, but that feels unclean.

2

There are 2 best solutions below

2
On BEST ANSWER

try as follow

To reuse the actionListener of quite button you can click quite button in windowClosing .

to click a button from code call doclick() method. example

quitButton.doClick();
0
On

You want to add a WindowListener to the JFrame which will let you get close events.

frame.addWindowListener(new MyWindowListener());
...
public class MyWindowListener extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
      // do something
    }
}