2012-12-13 63 views
8

我在學習如何製作JAVA程序,並且正在使用Swing。我試圖在窗口的左上角放置一個按鈕,並且它會繼續到頂部中心。在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); 
} 

我在做什麼錯或有沒有更好的方法來做到這一點? 請幫助

+1

'frame.setDefaultCloseOperation(3);'不要使用幻數。 J2SE爲這些值描述性地命名常量。 –

回答

2

,而不是

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

如果使用

addButtonGUI(panel, new JButton(), "test", 0, 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填充)。