关于swing:java BoxLayout面板的对齐方式

java BoxLayout panel's alignment

我四处浏览,但找不到适合我情况的解决方案。 我有一个在对话框中显示的面板:

1
2
3
4
5
6
7
8
9
10
11
12
//create dialog panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(headerPanel);
panel.add(type1Panel);
panel.add(type2Panel);
panel.add(type3Panel);
panel.add(type4Panel);
panel.add(type5Panel);
panel.add(type6Panel);

int result = JOptionPane.showConfirmDialog(null, panel,"Please enter values.", JOptionPane.OK_CANCEL_OPTION);

最后两个面板(类型5和类型6)的大小相等,因此看起来不错。 但是,页眉和前4个面板的大小不同,我希望它们都对齐。 到目前为止,我还没有找到解决此问题的好方法。

问题是,我如何左对齐前5个面板,而不对齐最后两个? 如果没有,我该如何将它们全部对齐? setalignmentx()不适用于面板。 我曾尝试使用GridLayout,但是gui的主窗口的宽度相当大,无法很好地适应屏幕,因此BoxLayout沿Y轴。谢谢您的帮助或建议。


这是一个示例,它将使添加到用作容器的面板的所有JPanel保持左对齐。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   JPanel a = new JPanel();
   JPanel b = new JPanel();
   JPanel c = new JPanel();

   a.setBackground( Color.RED );
   b.setBackground( Color.GREEN  );
   c.setBackground( Color.BLUE );

   a.setMaximumSize( new Dimension(  10, 10) );
   b.setMaximumSize( new Dimension(  50, 10) );

   a.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
   b.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
   c.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0

   JPanel panel = new JPanel();
   panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
   panel.add(a);
   panel.add(b);
   panel.add(c);

   int result = JOptionPane.showConfirmDialog(null, panel,"Please enter values.", JOptionPane.OK_CANCEL_OPTION);


创建一个水平javax.swing.Box对象以包含每个typenPanel对象。使用水平支柱和胶水,您可以做任何您想做的事情:

1
2
3
4
Box  b1 = Box.createHorizontalBox();
b1.add( type1Panel );
b1.add( Box.createHorizontalGlue() );
panel.add( b1 );

为简单起见,请编写一个辅助方法来为您执行此操作:

1
2
3
4
5
6
7
8
private Component leftJustify( JPanel panel )  {
    Box  b = Box.createHorizontalBox();
    b.add( panel );
    b.add( Box.createHorizontalGlue() );
    // (Note that you could throw a lot more components
    // and struts and glue in here.)
    return b;
}

然后:

1
2
3
panel.add( leftJustify( headerPanel ) );
panel.add( leftJustify( type1Panel ) );
panel.add( leftJustify( type2Panel ) );

等等。您可以在每条生产线上添加更多的组件,胶水和撑杆,从而获得更高的评价。我很幸运能深深地嵌套垂直和水平框,并且当我想在一个框内多次进行相同的布局时编写辅助方法。对您可以做的事情没有任何限制,可以根据需要混合组件,支柱和胶水。

我敢肯定有更好的方法来完成所有这些工作,但是我还没有找到它。动态调整大小可以让文本短的用户使用一个小窗口,而文本很多的用户可以调整它的大小,以适应所有情况。


您应该在面板上使用setAlignmentX,因为它可用于JPanel。方法setAlignmentXsetAlignmentYJPanel扩展的JComponent中找到。它起作用了...我有使用这些方法在BoxLayout中对齐JPanels的代码。

好的,好的,在我回答时编辑您的问题:)

代替使用JPanel尝试使用Box。我发现Box类作为容器非常有用。从API:

A lightweight container that uses a BoxLayout object as its layout
manager. Box provides several class methods that are useful for
containers using BoxLayout -- even non-Box containers.

如果您还没有看到它,那么"如何使用BoxLayout"教程将非常有帮助。