以下範例展示了如何在基於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 Tw511.com ~"));
frame.getContentPane().add(panel, BorderLayout.CENTER);
}
}
執行上面範例程式碼,得到以下結果: