/*
* @(#) AddPanel.java
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AddPanel extends JFrame implements ActionListener {
private JPanel panel1;
private JPanel panel2;
private JButton button;
public AddPanel() {
panel1 = new JPanel();
panel1.setBackground(Color.gray);
Panel1Handler handler = new Panel1Handler();
panel1.addContainerListener(handler);
panel1.addComponentListener(handler);
add(panel1, BorderLayout.CENTER);
panel2 = new JPanel();
panel2.setBackground(Color.white);
panel2.setSize(200, 100);
button = new JButton("Add Panel");
button.addActionListener(this);
add(button, BorderLayout.SOUTH);
setSize(400, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event) {
panel1.add(panel2);
}
class Panel1Handler implements ContainerListener, ComponentListener {
public void componentAdded(ContainerEvent event) {
System.out.println("componentAdded");
panel1.repaint();
}
public void componentRemoved(ContainerEvent event) {
System.out.println("componentRemoved");
}
public void componentHidden(ComponentEvent event) {
System.out.println("componentHidden");
}
public void componentMoved(ComponentEvent event) {
System.out.println("componentMoved");
}
public void componentResized(ComponentEvent event) {
System.out.println("componentResized");
}
public void componentShown(ComponentEvent event) {
System.out.println("componentShown");
}
}
public static void main(String[] args) {
AddPanel application = new AddPanel();
}
}
注意:用JDK5.0版本编译执行。
程序运行后,单击 Add Panel 按钮后,可以正常添加并显示Panel2,但是当改变窗口大小后,Panel2就不能正常显示了,componentResized()方法里应该怎么添加什么代码?怎么写? 程序其它地方是不是也有错误?