0

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?

John W
  • 42
  • 1
  • 9

1 Answers1

1

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

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • I tried this before (red and dark red PNG files) and had the same result. Dark red shows, White shows instead of red. – John W Jan 19 '21 at 05:03
  • By 'red' DYM RGB(255,0,0) (I.E. `Color.RED`)? It works just fine here. – Andrew Thompson Jan 19 '21 at 05:05
  • My code works there? Or you have code that works? If so, please include it in your answer. I would love to know what is different. And yes, I was using FF0000 but no matter the color it showed up white. – John W Jan 19 '21 at 05:12
  • Well, I *wasn't* using hex numbers for the color, I was using `Color.RED`. And no, I did not use your (uncompilable(1)) code (snippet(1)) because neither was I intending on doing anything with the background color. 1) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Jan 19 '21 at 05:25