如何回應Swing窗口的窗口事件?

以下示例展示了如何在基於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.zaixian.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 xuhuhu.com ~"));

      frame.getContentPane().add(panel, BorderLayout.CENTER);
   }
}

執行上面示例代碼,得到以下結果:


上一篇: Swing框架和窗口示例 下一篇: Swing列表框示例