2015-04-03 61 views
1

我想在Java gui中使用GridBagLayout和GridBagConstraints。當我嘗試使用窗口生成器時,我收到以下消息:使用GridBagLayout將組件添加到父組件多次錯誤

The topPanelConstraints component is added to a parent component more than once. 

add(TitleLabel,topPanelConstraints); 
add(HomeButton,topPanelConstraints); 

不知道我在做什麼錯,謝謝你的幫助。 我正在使用Java Kepler,執行環境爲JavaSE-1.8。以下是我的代碼:

public class topPanel extends JPanel { 
    private JLabel TitleLabel; 
    private JButton HomeButton; 
    private JButton ExitButton; 

    public topPanel() 
    { 
     setBackground(new Color(51, 204, 0)); 
     setLayout(new GridBagLayout()); 
     GridBagConstraints topPanelConstraints = new GridBagConstraints(); 
     TitleLabel = new JLabel("title"); 
     TitleLabel.setFont(new Font("Arial", Font.PLAIN, 30)); 
     TitleLabel.setForeground(Color.WHITE); 

     topPanelConstraints.gridx = 0; 
     topPanelConstraints.gridy = 0; 
     add(TitleLabel,topPanelConstraints); 

     HomeButton = new JButton("home"); 
     HomeButton.setFont(new Font("Arial", Font.BOLD, 18)); 
     HomeButton.setBackground(new Color(224, 255, 255)); 
     topPanelConstraints.gridx = 1; 
     topPanelConstraints.gridy = 0; 
     add(HomeButton,topPanelConstraints); 

     ExitButton = new JButton("exit"); 
     ExitButton.setFont(new Font("Arial", Font.BOLD, 18)); 
     ExitButton.setBackground(new Color(224, 255, 255)); 
     topPanelConstraints.gridx = 2; 
     topPanelConstraints.gridy = 0; 
     add(ExitButton,topPanelConstraints); 
    } 

} 

回答

0

您可以聲明另一個GridBagConstraints var,那麼消息不會出現。

其實你可以忽略這個信息;這似乎是因爲您使用Window Builder在UI設計模式下打開此Java源代碼。