2014-10-10 101 views
1

我做了5个简单的按钮来查看GridBagLayout约束是如何工作的,并使它们像十字一样被设置。我试图尝试gridwidth为北,gbc.gridwidth = 2; (因为默认值是0,那么1和2是3列)。是不是应该占据3个横跨北方按钮所在的X轴的列?但是当你运行它时,按钮会重叠。请帮忙解释一下问题是什么?谢谢gridwidth和gridheight如何工作(Java guid GridBagLayout)?

JPanel jp = new JPanel(new GridBagLayout()); 
    GridBagConstraints gbc = new GridBagConstraints(); 

    JButton jb1 = new JButton("North"); 
    gbc.gridx = 0; 
    gbc.gridy = 0; 
    gbc.gridwidth = 2; //Here, it won't take up three columns just at the top where it sits 
    jp.add(jb1, gbc); 

    JButton jb2 = new JButton("West"); 
    gbc.gridx = 0; 
    gbc.gridy = 1; 
    jp.add(jb2, gbc); 

    JButton jb3 = new JButton("Center "); 
    gbc.gridx = 1; 
    gbc.gridy = 1; 
    jp.add(jb3, gbc); 

    JButton jb4 = new JButton("East"); 
    gbc.gridx = 2; 
    gbc.gridy = 1; 
    jp.add(jb4, gbc); 

    JButton jb5 = new JButton("South"); 
    gbc.gridx = 1; 
    gbc.gridy = 2; 
    jp.add(jb5, gbc); 

    add(jp); 

    setVisible(true); 

回答

4

的核心问题是,你有没有重新设置限制...

JButton jb1 = new JButton("North"); 
gbc.gridx = 0; 
gbc.gridy = 0; 
gbc.gridwidth = 2; //Here, it won't take up three columns just at the top where it sits 
jp.add(jb1, gbc); 

JButton jb2 = new JButton("West"); 
// Still using the gridwidth value from before... 
gbc.gridx = 0; 
gbc.gridy = 1; 
jp.add(jb2, gbc); 

这意味着gridwidth值仍设置为2对于所有其他控件.. 。

添加jb1后,尝试添加gbc = new GridBagConstraints();

而且,由于某些原因,gridwidth不为零索引,它开始于1,所以你可能想使用3,而不是...

JButton jb1 = new JButton("North"); 
gbc.gridx = 0; 
gbc.gridy = 0; 
gbc.gridwidth = 3; //Here, it won't take up three columns just at the top where it sits 
jp.add(jb1, gbc); 

gbc = new GridBagConstraints(); 
JButton jb2 = new JButton("West"); 
gbc.gridx = 0; 
gbc.gridy = 1; 
jp.add(jb2, gbc); 

现在,我可能是错的,但你似乎要努力使北按钮控制整个上排,像...

Fill

对于那些你需要的东西像...

JButton jb1 = new JButton("North"); 
gbc.gridx = 0; 
gbc.gridy = 0; 
gbc.gridwidth = 3; //Here, it won't take up three columns just at the top where it sits 
gbc.fill = GridBagConstraints.HORIZONTAL; 
jp.add(jb1, gbc); 

,以及...

+0

你会gridwidth孤单吗?在这种情况下,我认为它会做GridBagConstraints.HORIZONTAL同样的事情;通过在第一行占用3列。此外,每次单独按钮约束后,我是否必须重置? – 2014-10-10 06:39:42

+0

'gridwidth'就像是html的'table'中的'span',它描述了组件可以跨越/占用的列数 – MadProgrammer 2014-10-10 08:10:44