Java 如何将标签设置为即使在布局为空时也可见?此外,JFrame大小仍然默认为最小值

Java 如何将标签设置为即使在布局为空时也可见?此外,JFrame大小仍然默认为最小值,java,layout,jframe,jbutton,jlabel,Java,Layout,Jframe,Jbutton,Jlabel,这就是我的代码目前的样子: public TestFrame(){ setSize(x1, y1); /*where these are already defined*/ setLayout(new FlowLayout()); JLabel label = new JLabel("text"); label.setBorders(BorderFactory.createLineBorder(Color.BLUE)); label.setFont(new

这就是我的代码目前的样子:

public TestFrame(){
    setSize(x1, y1); /*where these are already defined*/
    setLayout(new FlowLayout());
    JLabel label = new JLabel("text");
    label.setBorders(BorderFactory.createLineBorder(Color.BLUE));
    label.setFont(new Font("Times New Roman", PLAIN, 14));
    label.setSize(width, height);
    label.setLocation(x, y)
    /* where these four variables are already defined */
    JButton testButton = new JButton("TestButton");
    testButton.setSize(bwidth, bheight);
    testButton.setLocation(bx, by);
    add(label);
    setVisible(true);
}
这主要是给了我一个问题,因为这是一个FlowLayout,它将TestFrame的大小设置为最小,并且没有将标签或按钮放在正确的大小或位置。 我被告知需要将布局设置为null,因此:

setLayout(null);
这里的主要问题是,虽然这确实将按钮放在了它应该放的地方,但它不会自动将测试框的大小设置为指定的大小,并且当标签可见时,显示正确的字体和所述字体的大小,整个文本周围有边框,由于某些原因,将布局设置为null会使标签完全消失


有没有解释为什么它会完全消失?如何解决此问题?

尝试将设置大小和设置位置替换为设置边界(x、y、宽度、高度); 空布局非常奇怪,我建议您使用LayoutManager

由于这是一个FlowLayout,它将测试框架的大小设置为最小

否,FlowLayout将考虑每个组件的首选尺寸

标签或按钮的尺寸或位置不正确

这是因为代码的结构是错误的。您使用的是setSize(…)方法,这意味着布局管理器无法正确完成其工作

代码的基本结构应为:

setLayout( new FlowLayout() );
...
add(label);
...
add(button);
pack(); // this will invoke the layout managers and size the frame correctly.
setVisible(true);