Calling function on windows close

人盡茶涼 提交于 2020-01-04 07:19:08

问题


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();
    }

回答1:


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.




回答2:


You can call your function on windowClosing method..

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.WindowConstants;

class WindowEventHandler extends WindowAdapter {
  public void windowClosing(WindowEvent evt) {
    System.out.println("Call your method here"); 
  }
}

public class TJFrame {

  public static void main(String[] args) {
    JFrame frame = new JFrame("Swing Frame");

    JTextBox label = new JLabel("This is a Swing frame", JLabel.CENTER);

    frame.add(label);

    frame.addWindowListener(new WindowEventHandler());
    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    frame.setSize(350, 200); // width=350, height=200
    frame.setVisible(true); // Display the frame
  }

}


来源:https://stackoverflow.com/questions/15499211/calling-function-on-windows-close

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!