-->

The component is added to a parent component more

2019-08-06 19:37发布

问题:

I want to use GridBagLayout and GridBagConstraints in Java gui. When I try to use the window builder, I get the following message:

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

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

don't know what am I doing wrong, thank you for your help. I am using Java Kepler, execution environment JavaSE-1.8. Below is my code:

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:

You can claim another GridBagConstraints var, then the messsage will not appear.

In fact, you can ignore this message; it appears because you used Window Builder to open this Java source code in UI design mode.