我遇到了一个非常烦人的问题。 JPanel 在组件之间添加了垂直间隙,我需要消除它。 我正在尝试得到这个(蓝线是我想要摆脱的空间):
看起来像这样:
这是我当前的类(class):
public class SummaryPanel extends JPanel
{
private JLabel bagelLabel;
private JLabel toppingLabel;
private JLabel coffeeLabel;
private JLabel shotsLabel;
private JLabel subtotal;
private JLabel tax;
private JLabel total;
private JPanel selectionsPanel;
private JPanel totalPanel;
public SummaryPanel()
{
bagelLabel = new JLabel("No bagel $0.00");
toppingLabel = new JLabel("No topping $0.00");
coffeeLabel = new JLabel("No coffee $0.00");
shotsLabel = new JLabel("(Includes 0 shots) $0.00");
subtotal = new JLabel("");
tax = new JLabel("");
total = new JLabel("");
setLayout(new GridLayout(2,1));
selectionsPanel = new JPanel();
selectionsPanel.setLayout(new GridLayout(4,1));
selectionsPanel.add(bagelLabel);
selectionsPanel.add(toppingLabel);
selectionsPanel.add(coffeeLabel );
selectionsPanel.add(shotsLabel );
totalPanel = new JPanel();
totalPanel.setLayout(new GridLayout(3,1));
totalPanel.add(subtotal);
totalPanel.add(tax);
totalPanel.add(total);
totalPanel.setVisible(false);
add(selectionsPanel);
add(totalPanel);
}
}
最佳答案
它由布局管理器控制。
setLayout(new GridLayout(2,1));
您正在使用 GridLayout,因此两个组件中的每一个都获得相同的空间。
selectionsPanel.setLayout(new GridLayout(4,1));
反过来,每个 JLabel 获得每个面板可用总空间的四分之一。
您可以使用 BorderLayout:
//setLayout(new GridLayout(2,1));
setLayout(new BorderLayout);
然后,当您将组件添加到您使用的面板时:
add(selectionsPanel, BorderLayout.PAGE_START);
add(totalsPanel, BorderLayout.PAGE_END);
现在将尊重首选尺寸。
关于Java如何禁用JPanel组件自动垂直调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40323773/