我定义了两个JPanel,p1和p2,先将p1添加到窗口上,然后点击按钮再将p2添加到p1上,下面写的这段代码为什么点击按钮后p2显示不出来,只有稍微改变下窗口大小p2才能显示出来?求解
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class panel extends JFrame{
private JPanel p1,p2;
private JButton b;
public panel(){
b = new JButton("add");
p1 = new JPanel();
p1.setSize(444, 444);
p1.setBackground(Color.BLACK);
p2 = new JPanel();
p2.setPreferredSize(new Dimension(200,200));
p2.setBackground(Color.RED);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
p1.add(p2);
p1.repaint();
}
});
this.add(p1, BorderLayout.CENTER);
this.add(b, BorderLayout.SOUTH);
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(0,0,400, 300);
this.setVisible(true);
}
public static void main(String[] args) {
new panel();
}
}
------解决方案--------------------------------------------------------
validate