1

I'm trying to skin a JToggleButton with 2 icons for the default and the toggle state. Why would it not change its display anyways, although I set an icon for both states?

package gui;

import java.awt.Image;

import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JToggleButton;

public class RepeatButton extends JToggleButton {


    private ImageIcon repeatIcon;
    private ImageIcon repeatIconUnchecked;


    public RepeatButton() {
        repeatIcon = new ImageIcon("media_repeat.png");
        repeatIcon.setImage(repeatIcon.getImage().getScaledInstance(repeatIcon.getIconWidth()/2, repeatIcon.getIconHeight()/2,Image.SCALE_AREA_AVERAGING));
        repeatIconUnchecked = new ImageIcon("media_repeat_uncheckedalt.png");
        repeatIconUnchecked.setImage(repeatIconUnchecked.getImage().getScaledInstance(repeatIconUnchecked.getIconWidth()/2, repeatIconUnchecked.getIconHeight()/2,Image.SCALE_AREA_AVERAGING));
        this.setIcon(repeatIcon);
        this.setDisabledIcon(repeatIconUnchecked);
        this.setBorder(null);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
nakih
  • 63
  • 6
  • 1
    By the time of deployment, those icons will likely become an [tag:embedded-resource]. That being the case, they must be accessed by `URL` instead of `File`. See the [info page](http://stackoverflow.com/tags/embedded-resource/info) for the tag, for a way to form the `URL` for the `ImageIcon`. – Andrew Thompson Jan 29 '14 at 23:18

1 Answers1

3

The disabled icon is the icon that will be used when your JToggleButton gets disabled by doing:

btn.setEnabled(false);

And has nothing to do with the isSelected state.

You can do it manually by changing the icon by using a listener for the selected state. Or you could use the setSelectedIcon() method for that.

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • 1
    @nakih: don't mistake inexperience for stupidity. You will get better at this with continued effort, but most important -- please *do* check out the API as this answer is readily obtained from this useful tool. – Hovercraft Full Of Eels Jan 29 '14 at 23:17
  • I did check. The fact I was disabling something by toggling the button was stuck in head. I misstook isSelected() as isDisabled(). – nakih Jan 29 '14 at 23:20