0

I need to know if there's anyway to change a JButton's icon when it has focus. I'm using Netbeans and I have the option to change the Icon when the mouse is hovering over the button, when the button is pressed, and when the button is selected, so it seems natural to have an option to change it when it has focus. But unfortunately, I can't seem to find it, can anyone help?

That seems good enough, thanks.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
S.A.Th.
  • 53
  • 2
  • 10

1 Answers1

1

You could give the JButton a FocusListener, and within the listener change the button's icon within the focusGained and focusLost methods.

button.addFocusListener(new FocusListener() {

    @Override
    public void focusLost(FocusEvent e) {
        AbstractButton btn = (AbstractButton) e.getSource();
        btn.setIcon(DEFAULT_BTN_ICON);
    }

    @Override
    public void focusGained(FocusEvent e) {
        AbstractButton btn = (AbstractButton) e.getSource();
        btn.setIcon(FOCUSED_BTN_ICON);
    }
});
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373