JPanel is added onto other Jpanel on togglebutton Click

后端 未结 1 1021
甜味超标
甜味超标 2021-01-26 07:33

I am trying to make a popup panel which is activated with the help of JToggleButton. I want the JPanel to be added onto the other Jpanel when ToggleButton is selected and hides

1条回答
  •  一整个雨季
    2021-01-26 08:25

    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.

    0 讨论(0)
提交回复
热议问题