从构造函数填充jPanel



我试图在jPanel1中填充jPanel2,从这个jPanel1的构造函数。像这样。

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,宽度= 0,身高= 0)的

我不能理解的是,当我从另一个按钮监听器添加这个Jbutton时,它工作得很好。我猜在JPanel1生命周期的某个时刻,jPanel2是有界的,但我不知道在哪里。有人能帮忙吗?谢谢!

JPanel默认使用FlowLayout。相反,您应该尝试使用BorderLayout

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

你所面临的最初的问题是,父容器(jPanel1)的大小是未知的,直到容器布局…最好让布局管理器来做那份工作;)

最新更新