Swing 示例 - 響應視窗事件



以下示例展示瞭如何在基於 Swing 的應用程式中響應視窗事件。

當用戶單擊框架的關閉按鈕時,我們可以使用以下選項。

  • DO_NOTHING_ON_CLOSE − 無操作。只需監聽 windowClosing 事件以執行進一步的操作。

  • HIDE_ON_CLOSE − 這是 JFrame 和 JDialog 的預設行為,當單擊關閉按鈕時會隱藏。

  • DISPOSE_ON_CLOSE − 隱藏並關閉視窗並釋放視窗使用的任何資源。

  • EXIT_ON_CLOSE − 使用 System.exit(0) 退出應用程式。

以下示例展示了 DO_NOTHING_ON_CLOSE 的用法。

示例

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 Tester");           
      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("Hello World"));

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

輸出

Change default icon of window
swingexamples_frames.htm
廣告
© . All rights reserved.