我正在使用GridBagLayout (当前)显示两行。我知道这个布局对于这个任务来说有点过分了,但我正在努力学习如何使用它。问题是,我已经将两个面板添加到两个单独的行中,并且在内容周围有一个巨大的间隙(参见下面的图像和代码):alt text http://www.imagechicken.com/uploads/1264533379009864500.png
Image background;
public Table(){
super();
ImageIcon ii = new ImageIcon(this.getClass().getResource("pokerTableV2.png"));
background = ii.getImage();
setSize(Constants.FRAME_WIDTH, Constants.TABLE_HEIGHT);
setLayout(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
constraints.fill = GridBagConstraints.HORIZONTAL;
JButton button = new JButton("hello world");
JPanel panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(800,100));
panel1.add(button, BorderLayout.CENTER);
panel1.setBackground(Color.yellow);
add(panel1, constraints);
constraints.gridx = 0;
constraints.gridy = 1;
JPanel middlePanel = new JPanel();
middlePanel.setPreferredSize(new Dimension(800,350));
middlePanel.add(button, BorderLayout.CENTER);
middlePanel.setBackground(Color.blue);
add(middlePanel, constraints);
}发布于 2010-01-27 08:03:09
不幸的是,对于GridBagLayout,如果内容没有填满它所在的整个容器,它将自动将其所有内容放在容器中。这就是为什么你会得到一个非常大的差距。
基本上有两种方法可以解决这个问题:
GridBagConstraints。当我试图避免居中的行为时,我在这方面的成功有限。GridBagLayout放在FlowLayout中,然后将FlowLayout的对齐方式设置为左上角,或者您想要的任何位置。上周的某个时候,我曾经问过,也回答过,this question自己。
因此,在本例中,您使用GridBagLayout将panel1和middlePanel直接添加到JFrame (?)中
JFrame (GridBagLayout)
- panel1
- middlePanel我建议使用这种替代结构,去掉所有额外的空间(如果你喜欢,也可以使用中心对齐)。
JFrame (FlowLayout)
- JPanel (GridBagLayout)
- panel1
- middlePanelHTH
发布于 2010-01-27 02:59:45
使用
constraints.fill = GridBagConstraints.BOTH;
constraints.weightx = 1d;
constraints.weighty = 1d;适用于weightx/weighty的JavaDoc表示:
指定如何分布额外的水平/垂直空间。
用于fill的JavaDoc
当组件的显示区域大于组件的请求大小时,将使用此字段。它确定是否调整组件的大小,如果是,如何调整。
https://stackoverflow.com/questions/2141594
复制相似问题