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 when the ToggleButton is deselected.
I have declared the JToggleButton and used ItemListener. But What is happening is when i select the ToggleButton a panel is created if i deselect and Select it again another JPanel is added again and so on and After 5 clicks , Nothing appears.
public static JPanel createDesignButtons(){
designButtonsPanel.setOpaque(false);
BoxLayout boxLayout = new BoxLayout(designButtonsPanel, BoxLayout.LINE_AXIS);
designButtonsPanel.setLayout(boxLayout);
mainButton.setIcon(Icons.venueIcon);
mainButton.setBorderPainted(false);
mainButton.setPreferredSize(new Dimension(40,40));
mainButton.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
if(ev.getStateChange()==ItemEvent.SELECTED){
designButtonsPanel.add(createButtonsDialog());
designButtonsPanel.validate();
} else if(ev.getStateChange()==ItemEvent.DESELECTED){
System.out.println("button is not selected");
}
}
});
designButtonsPanel.add(mainButton);
JLabel padding = new JLabel(" ");
padding.setPreferredSize(null);
JLabel divider = new JLabel("", Icons.dividerIcon, JLabel.CENTER);
divider.setPreferredSize(new Dimension(3,45));
designButtonsPanel.add(divider);
SwingUtilities.updateComponentTreeUI(designButtonsPanel);
return(designButtonsPanel);
}
The above code is showing the mainButton is togglebutton that i want action on and the DesignButtonPanel is the Panel which is parent.
public static JPanel createButtonsDialog(){
JPanel buttonsPanel = new JPanel();
buttonsPanel.setBorder(new LineBorder(Color.gray,1));
return buttonsPanel;
}
This class show the panel i would like to add onto parent panel
How can i get the Panel added only once when the JtoggleButton is Selected and hides when its Deselected?
The problem is you keep creating instances of your
JPanel
. You couldremove
theJPanel
if yourJToggleButton
is not selected and add an already created instance of yourJPanel
if the button is selected. See this simple example:You can see that
centerPanel
is only instantiated once.