📄 containeradapterdemo.java
字号:
import javax.swing.*;import java.awt.*;import java.awt.event.*;public class ContainerAdapterDemo extends JFrame implements ActionListener{ private JButton addButton; private JTextField jtf; private JPanel southPanel, centerPanel; private int count; public ContainerAdapterDemo() { 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. */ centerPanel = new JPanel(); centerPanel.addContainerListener(new ContainerHandler()); 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. The revalidate() *//* method is used to update the display when a button is added. */ public void actionPerformed(ActionEvent event) { centerPanel.add(new JButton("Button "+count)); centerPanel.revalidate(); ++count; }/* The ContainerListener is implemented as an inner class that *//* extends the ContainerAdapter class. Only the componentAdded() *//* is overridden. This method obtains a reference to the JButton *//* that was added to the centerPanel and updates the JTextField *//* to indicate which button was added. */ class ContainerHandler extends ContainerAdapter { public void componentAdded(ContainerEvent event) { JButton button = (JButton)event.getChild(); jtf.setText(button.getText()+" was added"); } } public static void main(String args[]) { ContainerAdapterDemo demo = new ContainerAdapterDemo(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -