gpt4 book ai didi

java - GridbagLayout 似乎忽略了组件大小

转载 作者:行者123 更新时间:2023-11-30 03:32:50 24 4
gpt4 key购买 nike

我是第一次使用GridBagLayout。我有一个 JFrame ,里面有 2 个面板。

  • 框架宽度为 1200,高度为 800。
  • 最左边的 JPanel 宽度为 800,高度为 800。
  • 最右边的面板宽度为 400,高度为 800。

当它们使用 GridBagLayout 渲染时,它们都以相同的大小显示。

这是代码:

public class DisplayFrame extends JFrame {
public DisplayFrame() {

//simple inheritance.
super(title);
setSize(new Dimension(1200, 800));
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);

addComponents();

}

public void addComponents(){

this.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();

gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new DisplayCanvas(), gbc);

gbc.gridx++;
add(new ControlContainer(), gbc);

}
}

public class DisplayCanvas extends JPanel{

public DisplayCanvas() {

setPreferredSize(new Dimension(800,800));
this.setBackground(Color.WHITE);
this.setVisible(true);

}

@Override
public Dimension getPreferredSize() {
return new Dimension(800, 800);
}

}
public class ControlContainer extends JPanel{

public ControlContainer() {
setPreferredSize(new Dimension(200,200));
setBackground(Color.GRAY);
setVisible(true);

}

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 800);
}
}

毫无疑问,我错过了一些非常明显的东西。

最佳答案

gbc.weightx = 1;gbc.weighty = 1; 会覆盖组件提供的大小调整提示。这基本上为两个组件提供了相同的权重,以填充 GridBagLayout 可用的剩余空间。

不要仅依赖大小调整提示,因为窗口的大小可以调整。

另外,请记住,框架有装饰,因此框架不会(也不应该是)1200x800。允许内容提供有关其所需内容的信息,并使用 pack 来确保可视区域满足您的需求,并且框架装饰打包在其周围。这将使您的窗口大小最终大于内容区域,但内容区域才是最重要的

关于java - GridbagLayout 似乎忽略了组件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28619238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com