JPanel is added onto other Jpanel on togglebutton Click

落爺英雄遲暮 提交于 2019-12-02 09:51:32

The problem is you keep creating instances of your JPanel. You could remove the JPanel if your JToggleButton is not selected and add an already created instance of your JPanel if the button is selected. See this simple example:

public class MainFrame extends JFrame {

private JPanel topPanel = new JPanel();
private JPanel centerPanel = new JPanel();
private JToggleButton toggleButton = new JToggleButton("Toggle");

public MainFrame() {
    this.setVisible(true);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setLayout(new BorderLayout());

    this.topPanel.setPreferredSize(new Dimension(100, 100));
    this.centerPanel.setPreferredSize(new Dimension(100, 100));
    this.toggleButton.setPreferredSize(new Dimension(100, 100));

    this.add(topPanel, BorderLayout.NORTH);
    this.add(centerPanel, BorderLayout.CENTER);
    this.add(toggleButton, BorderLayout.SOUTH);

    this.toggleButton.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if(e.getStateChange() == ItemEvent.SELECTED) {
                add(centerPanel, BorderLayout.CENTER);
            } else {
                remove(centerPanel);
            }
            pack();
        }
    });

    this.pack();
    this.setVisible(true);
}
}

You can see that centerPanel is only instantiated once.

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