I am trying to change the color of a JToggleButton
when it has been selected in a reliable, look and feel independent way.
If using the Metal L&F, t
When it using "Windows look and feel"; in Netbeans you have to do only two things.
In other way,
jToggleButton.setContentAreaFilled(false);
jToggleButton.setOpaque(true);
jToggleButton.setBackground(Color.red); //Your color here
That's all.:-)
You might see if setIcon()
is sufficient for your purpose, but you can also override paint()
in the ButtonUI delegate.
Addendum: @kleopatra's comment is well-taken: changing the UI delegate is not trivial. @mKorbel's recent example shows both the difficulty and versatility of the approach. Its essential advantage is look & feel independence.
Some less ambitious approaches are mentioned here.
If you would rather use an action listener instead of overriding methods in a UI you can just change the UI to a UI without any selectColor
properties.
Here is an example I used recently
private class FavouriteToggle extends JToggleButton {
public FavouriteToggle() {
setUI(new BasicToggleButtonUI()); //Removes selectColor
////Your Custom L&F Settings////
setBackground(new Color(255, 252, 92));
setForeground(Color.GRAY);
setText("Favourite");
setBorder(null);
setFocusPainted(false);
////Add your own select color by setting background////
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(((JToggleButton) e.getSource()).isSelected()) {
setForeground(Color.BLACK);
setBackground(new Color(255, 251, 0));
} else {
setBackground(new Color(255, 252, 92));
setForeground(Color.GRAY);
}
}
});
}
}
JToggleButton btn = new JToggleButton(...);
btn.setUI(new MetalToggleButtonUI() {
@Override
protected Color getSelectColor() {
return Color.RED;
}
});
You can simply force background color before each repaint - for that you have to alter paintComponent, check if button is toggled, set background depending on toggle state and, at last, let super class do the actual paint job:
public class ColoredToggleButton extends JToggleButton
{
@Override
public void paintComponent(Graphics g)
{
Color bg;
if (isSelected()){
bg = Color.GREEN;
} else {
bg = Color.RED;
}
setBackground(bg);
super.paintComponent(g);
}
}
"ToggleButton.selected" is wrong, it require "ToggleButton.select". And should be update to the component.
UIManager.put("ToggleButton.select", Color.WHITE);
SwingUtilities.updateComponentTreeUI(togglebuttonname);