JToggleButton background color when selected

196 Views Asked by At

I have a JTogglebutton where I set the initial background color to red. I have an action routine that flips between red and dark red. Basically, if the button is selected, it is red. Not selected, it is dark red.

The code runs, but whenever the toggle button is selected, it is colored white. So I flip between dark red and white instead.

redButton = new JToggleButton("", false);
redButton.setBackground(Color.decode("#400000"));
// Define ActionListener
ActionListener redListener = new ActionListener() {
   public void actionPerformed(ActionEvent actionEvent) {
      AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
      boolean selected = abstractButton.getModel().isSelected();
      if (selected)
         {
            abstractButton.setBackground(Color.decode("#FF0000"));
         } else { 
            abstractButton.setBackground(Color.decode("#400000"));
        }
      }
    };
redButton.addActionListener(redListener);
add(redButton);

What I have done: I did a lot of experimentation with code and got nowhere. I did a lot of internet searches but could not come up with a working example.

I am using Java 11. What do I need to change in code to get the behavior I am looking for?

1

There are 1 best solutions below

4
Andrew Thompson On

What do I need to change in code to get the behavior I am looking for?

The functionality you are trying to implement does not represent the path of least surprise for the end user. Why not instead use a colored icon for each of the normal and selected states?

Green (selected) Toggle Button Red (unselected) Toggle Button