I have a problem when i use Card Layout and toggle buttons. I want to change the background button when pressed for example:
private void togglebtnActionPerformed(java.awt.event.ActionEvent evt){
if(togglebtn.isSelected()){
togglebtn.setBackground(Color.green);}
else{
togglebtn.setBackground(Color.red);}
}
And by putting this togglebtn on a normal JFrame it works. If i use a Panel with CardLayout and put this togglebtn on this panel with CardLayout it doesn't work.
private void cbItemStateChanged(java.awt.event.ItemEvent evt){ //cb is the combobox i use to switch the two panels
CardLayout cl = (CardLayout) (displaypane.getLayout()); //displaypane is the panel in which i used the CardLayout
if (cb.getSelectedIndex() == 0){
cl.show(displaypane, "card1"); //card1 is the first panel in displaypane
} else {
cl.show(displaypane, "card2"); //card2 is the second panel in displaypane
}
}
Now if i use the same code i used before it doesn't work:
private void togglebtnActionPerformed(java.awt.event.ActionEvent evt){ //the toggle button is in card1
if(togglebtn.isSelected()){
togglebtn.setBackground(Color.green);}
else{
togglebtn.setBackground(Color.red);}
}
It only shows the red background but not the green one, so the togglebutton can't be selected. What's the difference of having a CardLayout?
I cannot explain the problem you have with CardLayout
here. In fact I could not get it work with simple JFrame
either.
But if you want to change background colors of a button you need to initialize it with:
togglebtn.setContentAreaFilled(false);
togglebtn.setOpaque(true);
Make it opaque and removing the fill of content area ensures that your ui look & feel wont over paint your defined background colors.