使用GridBagLayout将组件多次添加到父组件中

时间:2015-04-03 08:35:23

标签: java user-interface gridbaglayout windowbuilder

我想在Java gui中使用GridBagLayout和GridBagConstraints。当我尝试使用窗口构建器时,我收到以下消息:

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

}

1 个答案:

答案 0 :(得分:0)

您可以声明另一个GridBagConstraints var,然后不会出现消息。

实际上,您可以忽略此消息;看来是因为您使用Window Builder在UI设计模式下打开此Java源代码。