處理WindowEvent
的類應該實現此介面。該類的物件必須在元件中註冊。可以使用addWindowListener()
方法註冊該物件。
以下是java.awt.event.WindowListener
介面的宣告 -
public interface WindowListener
extends EventListener
編號 | 方法 | 描述說明 |
---|---|---|
1 | void windowActivated(WindowEvent e) |
將Window設定為活動Window時呼叫。 |
2 | void windowClosed(WindowEvent e) |
由於在Window上呼叫丟棄而關閉視窗時呼叫。 |
3 | void windowClosing(WindowEvent e) |
當使用者嘗試從Window的系統選單關閉Window時呼叫。 |
4 | void windowDeactivated(WindowEvent e) |
當Window不再是活動Window時呼叫。 |
5 | void windowDeiconified(WindowEvent e) |
當視窗從最小化狀態更改為正常狀態時呼叫。 |
6 | void windowIconified(WindowEvent e) |
當Window從正常狀態更改為最小化狀態時呼叫。 |
7 | void windowOpened(WindowEvent e) |
第一次使視窗可見時呼叫。 |
此介面從以下介面繼承方法 -
java.awt.EventListener
使用編輯器建立以下Java程式:WindowListenerDemo.java
package com.yiibai.swing.listener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class WindowListenerDemo {
private JFrame aboutFrame;
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public WindowListenerDemo(){
prepareGUI();
}
public static void main(String[] args){
WindowListenerDemo swingListenerDemo = new WindowListenerDemo();
swingListenerDemo.showWindowListenerDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING WindowListener範例(tw511.com)");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showWindowListenerDemo(){
headerLabel.setText("Listener in action: WindowListener");
JButton okButton = new JButton("OK");
aboutFrame = new JFrame();
aboutFrame.setSize(300,200);;
aboutFrame.setTitle("WindowListener範例");
aboutFrame.addWindowListener(new CustomWindowListener());
JPanel panel = new JPanel();
panel.setBackground(Color.white);
JLabel msglabel = new JLabel("歡迎您來到易百Swing教學"
,JLabel.CENTER);
panel.add(msglabel);
aboutFrame.add(panel);
aboutFrame.setVisible(true);
}
class CustomWindowListener implements WindowListener {
public void windowOpened(WindowEvent e) {
}
public void windowClosing(WindowEvent e) {
aboutFrame.dispose();
}
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) {
}
}
}
執行上面範例程式碼,得到以下結果: