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?