JFrame 按钮和 GridBagConstraints

JFrame Buttons and GridBagConstraints

为什么我的按钮约束不起作用?我查看了 Java 文档,正在做教程正在做的相同事情,但对我来说,无论我使用什么 gridx、y、宽度或填充,按钮都保持不变。有任何想法吗?这是我的代码:

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);
}
}

您当前的代码中未指定容器的 LayoutManager(JPanel 的默认设置是 FlowLayout)。如果你想在容器上使用 GridBagLayout,你必须明确指定 LayoutManager:

p = new JPanel(new GridBagLayout());
//or
p.setLayout(new GridBagLayout());