Search code examples
javaswingjframeawtwindowlistener

Calling function on windows close


Using Java: I have a GUI built using the netbeans GUI builder.

The GUI class was created by extending a jFrame

public class ArduinoGUI extends javax.swing.JFrame

and the GUI displayed using:

java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {                    
        new ArduinoGUI().setVisible(true);                    
    }
}

Therefore I don't have an actual frame object on which to call frame., so how in this case can I override the windowClosed function, because I have to call a specific function to tidy up a serial connection before the app exits.

Edit: here is the code explicit as answered below:

@Override
public void processWindowEvent(WindowEvent e) {
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
        arduino.close();
        System.out.println("Arduino Close()");
        dispose();
    }

Solution

  • Create "processWindowEvent" method in your class (which is subclass of JFRame) if you haven't already done. That method takes WindowEvent object as parameter. inside that method add an if block like this :

    if(e.getID() == WindowEvent.WINDOW_CLOSING){
    
        //...Do what you need to do just before closing
    
    }
    

    e is the WindowEvent object passed parameter to method.