java swing ContainerListener 示例,,package cn.o
分享于 点击 29770 次 点评:239
java swing ContainerListener 示例,,package cn.o
package cn.outofmemory.snippets.desktop;import java.awt.Component;import java.awt.Container;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ContainerEvent;import java.awt.event.ContainerListener;import javax.swing.JButton;import javax.swing.JFrame;public class ContainerListenerExample { public static void main(String args[]) { JFrame jFrame = new JFrame(); Container cPane = jFrame.getContentPane(); ContainerListener containerListener = new ContainerListener() { ActionListener actiListener = new ActionListener() { @Override public void actionPerformed(ActionEvent event) { System.out.println("Select: " + event.getActionCommand()); } }; @Override public void componentAdded(ContainerEvent event) { Component compChild = event.getChild(); if (compChild instanceof JButton) { JButton jButton = (JButton) compChild; jButton.addActionListener(actiListener); } } @Override public void componentRemoved(ContainerEvent event) { Component compChild = event.getChild(); if (compChild instanceof JButton) { JButton Jbutton = (JButton) compChild; Jbutton.removeActionListener(actiListener); } } }; cPane.addContainerListener(containerListener); cPane.setLayout(new GridLayout(3, 2)); cPane.add(new JButton("First")); cPane.add(new JButton("Second")); cPane.add(new JButton("Third")); cPane.add(new JButton("Fourth")); cPane.add(new JButton("Fifth")); jFrame.setSize(400, 300); jFrame.show(); }}
用户点评