[英]GridBagLayout padding
我正在使用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);
}
不幸的是,使用GridBagLayout
,如果內容沒有填充它所在的整個容器,它將自動將其所有內容集中在其容器中。 這就是為什么你會有一個非常大的差距。
基本上有兩種方法可以解決這個問題:
GridBagConstraints
。 在試圖避免集中行為時,我的成功有限。 GridBagLayout
放在FlowLayout
,然后將FlowLayout
的對齊方式設置為左上角或任何你想要的。 我上周某個時候曾問過並回答過這個問題 。
因此,在您的情況下,您使用GridBagLayout
將panel1
和middlePanel
直接添加到JFrame(?)
JFrame (GridBagLayout)
- panel1
- middlePanel
我會建議這個替代結構,以擺脫所有額外的空間(和中心對齊,如果你願意)。
JFrame (FlowLayout)
- JPanel (GridBagLayout)
- panel1
- middlePanel
HTH
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.