[英]Placing buttons in a specified location using swing in java
我正在努力學習如何制作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);
}
我做錯了什么或者有更好的方法嗎? 請幫忙
您需要將JPanel
的布局設置為GridBagLayout
以使用GridBagConstraints
:
JPanel panel = new JPanel(new GridBagLayout());
此外,由於您只有一個有效的“單元”,因此需要使用錨點並為JButton
設置weighty
以允許在Y軸上移動。
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weighty = 1.0;
我還要將fill
設置設置為NONE
:
gbc.fill = GridBagConstraints.NONE;
這樣按鈕就不會占據面板的整個寬度。 (2 = HORIZONTAL填充)。
代替
addButtonGUI(panel, new JButton(), "test", 1, 1);
}
如果你使用會發生什么
addButtonGUI(panel, new JButton(), "test", 0, 0);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.