问题描述
我第一次使用GridBagLayout
.我有一个JFrame
,里面有2个面板.
I am using GridBagLayout
for the first time. I have a JFrame
which has 2 panel's inside.
- 框架的宽度为1200,高度为800.
- 最左边的
JPanel
的宽度为800,高度为800. - 最右边的面板的宽度为400,高度为800.
- The frame is of width 1200 and height 800.
- The left most
JPanel
has the width of 800 and height of 800. - The right most panel has the width of 400 and height of 800.
使用GridBagLayout
渲染时,它们都以相同的大小显示.
When they are rendering using GridBagLayout
they are both being shown with equal size.
这是代码:
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);
}
}
毫无疑问,我遗漏了一些非常明显的东西.
No doubt I am missing something very obvious.
推荐答案
gbc.weightx = 1;
和gbc.weighty = 1;
覆盖了组件所提供的大小提示.这基本上为两个组件提供了相等的权重,以填充GridBagLayout
gbc.weightx = 1;
and gbc.weighty = 1;
are overriding the sizing hints your components are providing. This is basically providing equal weight to both components to fill the remaining space available to the GridBagLayout
不要仅仅依靠大小提示,因为可以调整窗口的大小.
Don't rely on the sizing hints alone, as the window could be resized.
另外,请记住,框架具有装饰,因此框架不会(也不应该)为1200x800.允许内容提供有关所需内容的信息,并使用pack
确保可见区域满足您的需求,并在其周围包装框架装饰.最终,这将使您的窗口尺寸大于内容区域,但是内容区域才是重要的
Also, remember, a frame has decorations, so the frame won't be (and shouldn't be) 1200x800. Allow the content to provide the information about what it needs and use pack
to ensure that the viewable area meets your needs and the frame decorations are packed around it. This will make you windows size, ultimately, larger then the content area, but the content area is what matters
这篇关于GridbagLayout似乎正在忽略组件大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!