问题描述
我对 Java Swing 很陌生。我在包含 2 个内部面板的“外部”面板上使用 y 轴 BoxLayout。在这里你可以看到这个基本代码,2个内板在盒子布局中获得相等的高度(第一个内板黄色,第二个内板橙色)
// main test frame
public class MainFrame extends JFrame {
public MainFrame()
{
this.setSize(500,500);
this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(1,1));
// outer panel: groupWrapPanel with BoxLayout
JPanel groupWrapPanel = new JPanel();
groupWrapPanel.setBackground(Color.blue);
groupWrapPanel.setLayout(new BoxLayout(groupWrapPanel,BoxLayout.Y_AXIS));
// inner panel 1: headerPanel (yellow)
JPanel headerPanel = new JPanel();
headerPanel.setBackground(Color.yellow);
groupWrapPanel.add(headerPanel);
// inner panel 2: headerNotesWrap (orange)
JPanel headerNotesWrap = new JPanel();
headerNotesWrap.setBackground(Color.orange);
groupWrapPanel.add(headerNotesWrap);
this.add(groupWrapPanel);
this.setVisible(true);
}
}
但是当我将单独的布局管理器添加到其中一个内面板时,外面板的布局发生了变化,并且两个内面板不再获得外面板高度的相等份额。我可以通过添加一行代码来做到这一点:
headerPanel.setLayout(new BorderLayout());
有人可以解释为什么当我为内面板指定布局管理器时外面板的布局会发生变化,以及如何防止这种情况发生。
谢谢。
编辑
“BoxLayout 将决定每个组件的首选大小。如果有额外的可用空间,它将平均分配空间,直到每个组件的最大大小。这将解释为什么每个面板在第一个中是 50/50案例。”
如果是这样,为什么我将 2 个内部组件从面板更改为标签,它们不再拉伸以填充外部面板内的可用空间?像这样:
公共类 MainFrame 扩展 JFrame {
public MainFrame()
{
// we're going to create what shall be kNown as a "Group Box",// which groups things together
this.setSize(500,500);
this.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(1,1));
// outer panel: groupWrapPanel with BoxLayout
JPanel groupWrapPanel = new JPanel();
groupWrapPanel.setBackground(Color.blue);
groupWrapPanel.setLayout(new BoxLayout(groupWrapPanel,BoxLayout.Y_AXIS));
// inner label 1
JLabel label1 = new JLabel("Label 1");
label1.setBackground(Color.yellow);
label1.setopaque(true);
groupWrapPanel.add(label1);
// inner label 2
JLabel label2 = new JLabel("Label 2");
label2.setBackground(Color.orange);
label2.setopaque(true);
groupWrapPanel.add(label2);
this.add(groupWrapPanel);
this.setVisible(true);
}
}
再次感谢
解决方法
我在您的代码中添加了以下内容:
setVisible(true);
System.out.println(headerPanel.getPreferredSize());
System.out.println(headerPanel.getMaximumSize());
System.out.println(headerNotesWrap.getPreferredSize());
System.out.println(headerNotesWrap.getMaximumSize());
并在使用 BorderLayout 时得到以下输出:
java.awt.Dimension[width=0,height=0]
java.awt.Dimension[width=2147483647,height=2147483647]
java.awt.Dimension[width=10,height=10]
java.awt.Dimension[width=32767,height=32767]
可以看到 BorderLayout 的最大尺寸比 FlowLayout 的大很多。
所以当额外的空间按比例分配时,BorderLayout 面板会得到更多。
一些可能的解决方案:
-
覆盖使用 BorderLayout 的面板的
getMaximumSize()
方法以返回适当的值。 -
使用 GridBagLayout。您还可以在一列中堆叠面板。
-
尝试使用 Relative Layout,它的功能类似于 BoxLayout,只是堆叠面板。