如何设置流式布局的 JPanel 的最大宽度?

How to set the maximum width of a flow-layouted JPanel?

如图:外层是JPanel_1和BorderLayout;左边是JPanel_1西边的JPanel_2,用的是GridBadLayout;在 JPanel_2 中有几个面板,每个面板包含几个 JButton.

问题是,由于 JPanel_3 使用 FlowLayout,我尝试将其设置为最大宽度,以便当按钮过多时自动换行。但是,无论JPanelsizemaximumSizepreferred size中的哪一个设置,都不起作用。按钮保持在一行,使 JPanel 对我来说太宽了。

有人有解决办法吗?谢谢!

您可以像这样扩展 FlowLayout 来限制首选宽度

import javax.swing.*;
import java.awt.*;

public class TestMaxWidthFlowLayout {

    public static void main(String[] args) {
        JFrame f=new JFrame();
        JPanel pButtons=new JPanel(new FlowLayout() {
            public Dimension preferredLayoutSize(Container target) {
                Dimension sd=super.preferredLayoutSize(target);

                sd.width=Math.min(200, sd.width);

                return sd;
            }
        });
        for (int i=0;i<20; i++) {
            pButtons.add(new JButton("b-"+i));
        }

        f.add(pButtons, BorderLayout.WEST);
        f.add(new JLabel("center"), BorderLayout.CENTER);

        f.setSize(500, 300);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

so that the buttons auto change line when there are too many.

您可以使用Wrap Layout。随着可用宽度的变化,它将动态地将组件流到新行。

WrapLayout 是 Fl​​owLayout 的扩展,它将在组件环绕时正确计算面板的首选大小。