我正在使用JFrame开发一个java GUI。我想关闭GUI框架并通过代码将其处理掉。 我已经实施了:
topFrame.addWindowListener(new WindowListener()
{
public void windowClosing(WindowEvent e)
{
emsClient.close();
}
public void windowOpened(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowActivated(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
});`
如何调用windowClosing事件?或者还有其他方式吗?
答案 0 :(得分:16)
这将以编程方式触发窗口关闭事件:
topFrame.dispatchEvent(new WindowEvent(topFrame, WindowEvent.WINDOW_CLOSING));
如果你想关闭你需要调用的帧:
topFrame.dispose();
答案 1 :(得分:3)
如何调用dispose()
方法?
答案 2 :(得分:2)
你需要这个:
yourFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
你可以在构造函数中添加该行(别忘了)。
答案 3 :(得分:2)
import java.awt.event.*;
import javax.swing.*;
class CloseFrame {
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JButton close = new JButton("Close me programmatically");
final JFrame f = new JFrame("Close Me");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setContentPane( close );
close.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
// make the app. end (programatically)
f.dispose();
}
} );
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}