我的UI分为两个面板,让我们称之为 NormalPanel 和 SpecialPanel 。 NormalPanel 应占用水平空间的25%, SpecialPanel 占另外75%。为实现这一点,我使用了
gridBagLayout.columnWeights = new double[] { 1, 3 };
结果:
我遇到的问题是由于 specialPanel 的属性。它是一个包含固定大小Panel的JScrollPane。这意味着只要JFrame变得足够大以显示整个固定大小的面板,它就会忽略重量分布,只显示整个面板。
问题:
如何阻止这种情况发生?
我用来创建示例的代码:
public MyWindow() {
GridBagLayout gbLayout = new GridBagLayout();
// This makes the first row take 100% of the space (We only have one row)
gbLayout.rowWeights = new double[] { 1 };
// This makes the second column take up 3 times as much space as the first
gbLayout.columnWeights = new double[] { 1, 3 };
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = gbc.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
// Initialize the panels
normalPanel = new JPanel();
normalPanel.setBackground(Color.red);
specialPanel = new SpecialPanel();
contentPanel = new JPanel(gbLayout);
gbc.gridx = 0;
gbc.gridy = 0;
contentPanel.add(normalPanel, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
contentPanel.add(specialPanel, gbc);
setContentPane(contentPanel);
setSize(1280, 720);
setMinimumSize(new Dimension(1280, 720));
setVisible(true);
}
public static void main(String[] args) {
MyWindow window = new MyWindow();
}
/**
*
* This panel has a ScrollPan which is displaying a fixed sized panel.
*
*/
public class SpecialPanel extends JPanel {
private JScrollPane scrollPane;
private JPanel scrollPaneView;
private JPanel fixedSizePanel;
public SpecialPanel() {
fixedSizePanel = new JPanel();
fixedSizePanel.setPreferredSize(new Dimension(1280,720));
fixedSizePanel.setMaximumSize(new Dimension(1280,720));
fixedSizePanel.setMinimumSize(new Dimension(1280,720));
fixedSizePanel.setBackground(Color.blue);
scrollPaneView = new JPanel(new FlowLayout());
scrollPaneView.add(fixedSizePanel);
scrollPane = new JScrollPane(scrollPaneView);
scrollPane.setHorizontalScrollBarPolicy(scrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(scrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.setLayout(new GridLayout(1,1));
this.add(scrollPane);
}
}
}
答案 0 :(得分:2)
GridBagLayout是...... 违反直觉的以及它分配空间的方式。它首先“询问”组件他们想要的大小,并给他们那个空间,只有在那之后才是基于权重分配的剩余空间。
要解决此问题,请扩展您要添加到GridBagLayout的面板,并覆盖它们的getPrefferedSize()
方法。
@Override
public Dimension getPreferredSize() {
return new Dimension();
}
现在,面板将“告诉”他们不需要任何空间的布局,因此布局将根据权重分配所有空间。