I am trying to change the color of a JToggleButton when it has been selected in a reliable, appearance-independent manner.
When using Metal L & F, using UIManager is the approach:
UIManager.put("ToggleButton.selected", Color.RED);
Note Iyy pointed out that I had a typo in the property name above, but I will leave it higher for people who get here, but the actual property name should be:
UIManager.put("ToggleButton.select", Color.RED);
However, this does not work in my current Look and Feel (currently Windows XP). After some further analysis, it seems that the appearance of the system in Windows (still XP) does not use any of the UIManager properties UIManager for ToggleButton for ToggleButton in general, or at least it does not provide them (there is a quick online example to find all property keys from UIManager , which in this example is explicitly limited in the Color properties).
I tried to set the background color:
Action action = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { } }; JToggleButton button = new JToggleButton(action);
Not only does not change the selected state, but does not even affect the unselected state.
I tried to change the background color only after receiving the action:
@Override public void actionPerformed(ActionEvent e) { JToggleButton button = (JToggleButton)e.getSource(); if (button.isSelected())
None of this works. The only thing I found to work requires that I draw a button myself in the selected state (which leads to a working example, although non-standard):
private class ColoredToggleButton extends JToggleButton { ColoredToggleButton(Action action, Color color) { super(action); setBackground(color); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); if (this.isSelected()) { int w = getWidth(); int h = getHeight(); String s = getText();
This is slightly modified from the comment in this Java bug report . Interesting (funny?) In statements that were corrected in 1998.
Does anyone know of a more convenient, L&F independent way to set the background color of the selected JToggleButton?