ContainerListener
介面用於接收容器事件,處理容器事件的類需要實現此介面。
以下是java.awt.event.ContainerListener
介面的宣告 -
public interface ContainerListener
extends EventListener
編號 | 方法 | 描述說明 |
---|---|---|
1 | void componentAdded(ContainerEvent e) |
將元件新增到容器時呼叫。 |
2 | void componentRemoved(ContainerEvent e) |
從元件中刪除元件時呼叫。 |
該類從以下介面繼承方法 -
java.awt.event.EventListener
使用編輯器建立以下Java程式:ContainerListenerDemo.java
package com.yiibai.swing.listener;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ContainerListenerDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public ContainerListenerDemo() {
prepareGUI();
}
public static void main(String[] args) {
ContainerListenerDemo swingListenerDemo = new ContainerListenerDemo();
swingListenerDemo.showContainerListenerDemo();
}
private void prepareGUI() {
mainFrame = new JFrame("Java SWING ContainerListener範例(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 showContainerListenerDemo() {
headerLabel.setText("Listener in action: ContainerListener");
JPanel panel = new JPanel();
panel.setBackground(Color.blue);
panel.addContainerListener(new CustomContainerListener());
JLabel msglabel = new JLabel("歡迎您來到易百網Swing教學.", JLabel.CENTER);
panel.add(msglabel);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
class CustomContainerListener implements ContainerListener {
public void componentAdded(ContainerEvent e) {
statusLabel.setText(statusLabel.getText() + e.getComponent().getClass().getSimpleName() + " added. ");
}
public void componentRemoved(ContainerEvent e) {
statusLabel.setText(statusLabel.getText() + e.getComponent().getClass().getSimpleName() + " removed. ");
}
}
}
執行上面範例程式碼,得到以下結果: