如何编写容器侦听器
在将组件添加到容器或从容器中删除组件之后,Container
就会触发容器事件。这些事件仅用于通知-无需容器侦听器即可成功添加或删除组件。
下面的示例演示了容器事件。通过点击“添加按钮”或“删除按钮**”,您可以在窗口底部的面板中添加按钮或从中删除按钮。每次在面板上添加或删除按钮时,面板都会触发容器事件,并通知面板的容器侦听器。侦听器在窗口顶部的文本区域中显示描述性消息。
Try this:
-
单击启动按钮以使用Java™Web 开始(下载 JDK 7 或更高版本)运行 ContainerEventDemo。另外,要自己编译和运行示例,请查阅example index。
-
点击标有“添加按钮”的按钮。
您将看到一个按钮出现在窗口底部附近。容器侦听器通过在窗口顶部显示“已将 JButton#1 添加到 javax.swing.JPanel”来对所添加的组件事件做出反应。 -
单击标有 删除按钮 的按钮。
这将从面板上删除最近添加的按钮,从而使容器侦听器接收到已删除组件的事件。
您可以在ContainerEventDemo.java中找到该演示的代码。这是演示的容器事件处理代码:
public class ContainerEventDemo ... implements ContainerListener ... {
...//where initialization occurs:
buttonPanel = new JPanel(new GridLayout(1,1));
buttonPanel.addContainerListener(this);
...
public void componentAdded(ContainerEvent e) {
displayMessage(" added to ", e);
}
public void componentRemoved(ContainerEvent e) {
displayMessage(" removed from ", e);
}
void displayMessage(String action, ContainerEvent e) {
display.append(((JButton)e.getChild()).getText()
+ " was"
+ action
+ e.getContainer().getClass().getName()
+ newline);
}
...
}
容器侦听器 API
对应的适配器类为ContainerAdapter.
Method | Purpose |
---|---|
componentAdded(ContainerEvent) | 在将组件添加到侦听容器后立即调用。 |
componentRemoved(ContainerEvent) | 从侦听容器中删除组件后立即调用。 |
Method | Purpose |
---|---|
Component getChild() | 返回其添加或移除触发了此事件的组件。 |
Container getContainer() | 返回引发此事件的容器。您可以使用此方法代替getSource 方法。 |
使用容器侦听器的示例
下表列出了使用容器侦听器的示例。
Example | Where Described | Notes |
---|---|---|
ContainerEventDemo | This section | 报告在单个面板上发生的所有容器事件,以演示引发容器事件的情况。 |