2016-05-04 56 views
0

我有一个错误在那里我的gridx和gridy从GridBoxConstraints什么也不做。我有我想要添加和更改的位置的多个对象,但是他们都不发生变化,只是停留在我留在了首位,好像我从来没有使用过grix和gridy。的gridx和Gridy不改变任何东西

public class Applet extends JApplet{ 
private JButton b1; 
private JButton b2; 
private JFrame f; 
private JPanel p; 
private JRadioButton r; 
private JRadioButton r1; 
//private JTextField demoField; 
GridBagConstraints c =new GridBagConstraints(); 


public Applet() 
{ 
    gui(); 
} 
public void gui() 
{ 
    f=new JFrame("Applet!"); 
    f.setVisible(true); 
    f.setSize(500,500); 
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    p = new JPanel(); 
    p.setVisible(true); 

    //demoField = new JTextField(); 



    r = new JRadioButton("Leave a message!!"); 
    r1 = new JRadioButton("Draw a shape!!"); 

    b1 = new JButton("Button!"); 
    b1.setVisible(true); 
    b2 = new JButton("Button 2!"); 
    b2.setVisible(true); 
    r1.setVisible(true); 
    r.setVisible(true); 
    //setting grid numbers 
    c.gridx=0; 
    c.gridy = 0; 
    //adding to frame 
    p.add(b2,c); 
    //setting grid numbers 
    c.gridx = 5; 
    c.gridy = 2; 
    p.add(r1,c); 
    //setting grid numbers 
    c.gridx = 5; 
    c.gridy = 5; 

    p.add(r,c); 
    //setting grid numbers 
    c.gridx = 0; 
    c.gridy = 0; 
    p.add(b1,c); 

    //p.add(demoField); 
    f.add(p); 

} 

回答

0

gridxgridy进行有意义的使用,你也需要使用gridwidthgridheight。在GridBagLayout,细胞(因此行和列)电网没有一个固定的大小,但查询的内容首选大小,然后给他们,通过它们的权重来确定额外的空间(另一个约束参数 - 一如既往详情请参阅fine documentation)。

此外,虽然它是确定重用对多个对象的GridBagConstraints,这是混淆重用之前修改,而不会重置所有的域(有些是默认值为0)的。最简单的方法是为下一个子组件创建另一个约束对象(如果它们不同)。

所以:

b1 = new JButton("Button!"); 
b1.setVisible(true); 
b2 = new JButton("Button 2!"); 
b2.setVisible(true); 
r1.setVisible(true); 
r.setVisible(true); 
//setting grid numbers 
c.gridx = 0; 
c.gridy = 0; 
c.gridwidth = 5; 
c.gridheight = 2; 

//adding to frame 
p.add(b2,c); 
c = new GridBagConstraints(); 
//setting grid numbers 
c.gridx = 5; 
c.gridy = 2; 
p.add(r1,c); 
.... 

等。

GridBagLayout的布局非常复杂,从你的例子来看,你可能想要一些完全不同的东西:如果你希望有一个固定大小的网格,并且希望网格中有空白的“跳过”行和列,使用GridLayout,而不是GridBagLayout。

相关问题