The component is added to a parent component more than once error using GridBagLayout

霸气de小男生 提交于 2020-02-25 07:44:03

问题


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.



来源:https://stackoverflow.com/questions/29428865/the-component-is-added-to-a-parent-component-more-than-once-error-using-gridbagl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!