FlowLayout占用太多垂直空间,改变高度

问题描述

我有 JFrame,它使用 FlowLayout 表示按钮,BoxLayout 表示 JFrame,看起来像这样:

enter image description here

我需要它看起来像这样:

enter image description here

出于某种原因,按钮(绿色)的 JPanel 占用了太多空间,而红色面板上的标签都在同一行上,而不是每个都在不同的行上。

我的代码如下:

import javax.swing.*;
import java.awt.*;
 
public class ButtonsTest extends JFrame {
    private JButton button1 = new JButton("Button1");
    private JButton button2 = new JButton("Button2");
    private JButton button3 = new JButton("Button3");
    private JButton button4 = new JButton("Button4");

    private JPanel panel = new JPanel(new FlowLayout());
    private JPanel otherPanel = new JPanel();


    public Buttonstest()  {

        setPreferredSize(new Dimension(200,200));
        setMinimumSize(new Dimension(200,200));
        setVisible(true);
        setDefaultCloSEOperation(EXIT_ON_CLOSE);

        panel.add(button1);
        panel.add(button2);
        panel.add(button3);
        panel.add(button4);

        panel.setBackground(Color.GREEN);
        add(panel);

        setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));

        otherPanel.add(new Label("1"));
        otherPanel.add(new Label("2"));
        otherPanel.add(new Label("3"));
        otherPanel.setBackground(Color.RED);

        add(otherPanel);

        pack();
    }

    public static void main(String[] args) {
        ButtonsTest test = new Buttonstest();
    }
}

我的错误是什么?

解决方法

由于某种原因,按钮的 JPanel(绿色)占用了太多空间

使用 BoxLayout 时,当有额外空间可用时,组件将增长到最大大小。所以额外的空间分配给红色和绿色面板。

不要将内容窗格的布局设置为使用 BoxLayout。

而红色面板上的标签都在同一行,而不是每个都在不同的行。

默认情况下,JPanel 使用 Flow layout

解决方案是使用 JFrame 的默认 BorderLayout

然后使用以下命令将绿色面板添加到框架中:

add(panel,BorderLayout.PAGE_START);

然后对于“otherPanel”,您可以使用BoxLayout

otherPanel.setLayout( new BoxLayout(otherPanel,BoxLayout.Y_AXIS) );

然后使用以下命令将“otherPanel”添加到框架中:

add(otherPanel,BorderLayout.CENTER);

此外,应在框架可见之前将组件添加到框架中。所以 setVisible(...) 语句应该是构造函数中的最后一条语句。