📄 containereventdemo.java
字号:
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class ContainerEventDemo extends JFrame implements ContainerListener, ActionListener{ private JButton addButton; private JTextField jtf; private JPanel southPanel, centerPanel; private int count; public ContainerEventDemo() { count = 0; /* A JButton and a JTextField are added to a JPanel. *//* The JPanel is placed in the South quadrant of the frame. */ addButton = new JButton("add"); addButton.addActionListener(this); jtf = new JTextField(20); jtf.setEditable(false); southPanel = new JPanel(); southPanel.add(addButton); southPanel.add(jtf);/* The centerPanel registers a ContainerListener. *//* The ContainerEventDemo class itself serves as the *//* ContainerListener so the addContainerListener() method *//* is passed the "this" reference. */ centerPanel = new JPanel(); centerPanel.addContainerListener(this); getContentPane().add(southPanel, BorderLayout.SOUTH); getContentPane().add(centerPanel, BorderLayout.CENTER); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 500, 200); setVisible(true); }/* When the "add" button is pressed, a new JButton is placed *//* on the centerPanel. This action generates a ContainerEvent *//* which is sent to the componentAdded() method. */ public void actionPerformed(ActionEvent event) { centerPanel.add(new JButton("Button "+count)); centerPanel.revalidate();//使生效 ++count; }/* The componentAdded() method obtains a reference to the JButton *//* that was added to the centerPanel and updates the JTextField *//* to indicate which button was added. */ public void componentAdded(ContainerEvent event) { JButton button = (JButton)event.getChild(); jtf.setText(button.getText()+" was added"); }/* The componentRemoved() method is not used in this example but *//* an implementation must be provided anyway. It is implemented *//* as a stub method. This could have been avoided if the *//* ContainerAdapter class had been used. */ public void componentRemoved(ContainerEvent event) {} public static void main(String args[]) { ContainerEventDemo adj = new ContainerEventDemo(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -