0

我试图从这个 jPanel1 的构造函数中填充 jPanel1 内的 jPanel2。像这样的东西。

public jPanel1(){

    initComponents(); // here is created the jPanel2
    JButton jb= new JButton();
    jb.setBounds(new java.awt.Rectangle(0, 22, 400, 270));
    this.jPanel2.add(jb);
}

Jbutton 未显示。无论如何,当我从构造函数打印 jPanel2 边界时,我得到了这个:

'java.awt.Rectangle[x=0,y=0,width=0,height=0]'

我无法理解的是,例如,当我从另一个按钮侦听器添加此 Jbutton 时,它运行良好。我猜想在 JPanel1 生命周期的某个时刻, jPanel2 是有界的,但我不知道在哪里。有人可以帮忙吗?谢谢!

4

1 回答 1

1

JPanel默认情况下使用FlowLayout. 相反,您应该尝试使用BorderLayout

public jPanel1(){
    initComponents(); // here is created the jPanel2
    JButton jb= new JButton();
    jPanel2.setLayout(new BorderLayout());
    this.jPanel2.add(jb);
}

您面临的最初问题是父容器 ( jPanel1) 的大小在容器布置好之前是未知的......最好让布局管理器在那里工作;)

于 2013-05-27T11:45:55.853 回答