JFrame按钮和GridBagConstraints

时间:2015-05-03 00:01:59

标签: java swing jpanel gridbaglayout

为什么我的按钮限制不起作用?我查看了Java Docs,并且我正在做同样的教程,但对我来说,无论我使用什么gridx,y,width或fill,按钮都保持不变。有任何想法吗?这是我的代码:

class MyWindow
{
public static void main(String [] arg)
{
    MyJFrame f = new MyJFrame("My GUI 2015");
    f.setVisible(true);
    f.setSize(10, 20);
    f.add(f.p);
}
}

public class MyJFrame extends JFrame {

public JPanel p;
JButton close = new JButton("close");
JButton drawing = new JButton("drawing");
JButton image = new JButton("image");
JButton browser = new JButton("browser");

public MyJFrame(String title) {
    super(title);
    p = new JPanel();
    buildButtons();
}

void buildButtons() {       
    GridBagConstraints c = new GridBagConstraints();

    c.insets = new Insets(0,40,0,150);
    c.gridx = 0;
    c.gridy = 0;
    p.add(drawing, c);
    c.gridx = 2;
    c.gridy = 0;
    p.add(close, c);
    c.insets = new Insets(50,225,50,150);
    c.gridx = 0;
    c.gridy = 1;
    p.add(image, c);
    c.insets = new Insets(0,125,0,125);
    c.gridx = 0;
    c.gridy = 100;
    c.gridwidth = 3;
    c.fill = GridBagConstraints.HORIZONTAL;
    p.add(browser, c);
}
}

1 个答案:

答案 0 :(得分:4)

当前代码中未指定容器的LayoutManager(JPanel的默认值为FlowLayout)。如果要在容器上使用GridBagLayout,则必须显式指定LayoutManager:

p = new JPanel(new GridBagLayout());
//or
p.setLayout(new GridBagLayout());
相关问题