【问题标题】:How to set the maximum width of a flow-layouted JPanel?如何设置流布局 JPanel 的最大宽度?
【发布时间】:2015-04-13 12:47:09
【问题描述】:

如图所示:外部为JPanel_1,BorderLayout;左边是JPanel_1 西边的JPanel_2,它使用GridBadLayout; JPanel_2 中有几个面板,每个面板包含几个JButton

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

谁有解决方案?谢谢!

【问题讨论】:

    标签: java swing layout-manager flowlayout


    【解决方案1】:

    您可以像这样扩展 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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      这样按钮太多时会自动换行。

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

      WrapLayout 是 Fl​​owLayout 的扩展,它会在组件包装时正确计算面板的首选尺寸。

      【讨论】:

      • 我试过你的,tabbedPane 还是有一些问题。因此,受您和 SanisiavL 的启发,我终于自己扩展了 FlowLayout。
      猜你喜欢
      • 2012-02-10
      • 2018-01-09
      • 2018-09-02
      • 2014-10-30
      • 1970-01-01
      • 2016-03-09
      • 2012-08-01
      • 2011-08-20
      • 1970-01-01
      相关资源
      最近更新 更多