使用java中的swing将按钮放在指定位置

时间:2012-12-13 19:55:53

标签: java swing jpanel layout-manager gridbaglayout

我正在尝试学习如何制作JAVA程序,而我正在使用Swing。我试图在窗口的左上角放置一个按钮,它会一直到达顶部中心。

public void createGUI(){
    JFrame frame = new JFrame("My Project");
    frame.setDefaultCloseOperation(3);
    frame.setSize(400, 350);
    frame.setVisible(true);

    JPanel panel = new JPanel();

    frame.add(panel);

    addButtonGUI(panel, new JButton(), "test", 1, 1);
}

public void addButtonGUI(JPanel panel, JButton button, String text, int x, int y){
    GridBagConstraints gbc = new GridBagConstraints();
    button.setText(text);
    button.setEnabled(true);
    gbc.gridx = x;
    gbc.gridy = y;
    gbc.gridwidth = 2;
    gbc.weightx = 1.0D;
    gbc.fill = 2;
    panel.add(button, gbc);
}

我做错了什么或者有更好的方法吗? 请帮忙

2 个答案:

答案 0 :(得分:7)

您需要将JPanel的布局设置为GridBagLayout才能使用GridBagConstraints

JPanel panel = new JPanel(new GridBagLayout());

另外,由于您只有一个有效的“单元格”,因此您需要使用锚点并为weighty设置JButton以允许在Y轴上移动。

gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weighty = 1.0;

另外,我会将fill设置为NONE

gbc.fill = GridBagConstraints.NONE;

使按钮不占据面板的整个宽度。 (2 = HORIZONTAL 填充)。

答案 1 :(得分:2)

而不是

addButtonGUI(panel, new JButton(), "test", 1, 1);
}

如果您使用

会发生什么
addButtonGUI(panel, new JButton(), "test", 0, 0);
}