以下示例展示了如何在基于Swing的应用程序中响应窗口事件。
当用户单击框架的关闭按钮时,可以使用以下选项。
DO_NOTHING_ON_CLOSE
- 无动作。只需监听窗口关闭事件,采取进一步操作措施。HIDE_ON_CLOSE
- 它是单击关闭按钮时要隐藏的JFrame和JDialog的默认行为。DISPOSE_ON_CLOSE
- 隐藏并关闭窗口并释放窗口使用的所有资源。EXIT_ON_CLOSE
- 使用System.exit(0)
退出应用程序。
以下示例显示了使用DO_NOTHING_ON_CLOSE
的情况。
示例
package com.yiibai.swingdemo;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingTester {
public static void main(String[] args) {
createWindow();
}
private static void createWindow() {
JFrame frame = new JFrame("响应Swing窗口的窗口事件");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.addWindowListener(new WindowListener() {
public void windowOpened(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
});
createUI(frame);
frame.setSize(560, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static void createUI(JFrame frame){
JPanel panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
panel.add(new JLabel("Welcome to Yiibai.com ~"));
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
执行上面示例代码,得到以下结果: