2

I'd like to change the appearance of a button when it's in pressed/clicked/selected state.

To be more specific, I'd like to change it's border to BorderFactory.createLoweredBevelBorder() when it' is pressed/clicked/selected.

How can I do this?

Sebass van Boxel
  • 2,514
  • 1
  • 22
  • 37

2 Answers2

3

Please see the code below. It sets the border when pressed and resets it when released. You can also do this on mouseEntered / mouseExited.

button.addMouseListener(new MouseAdapter() {
  public void mousePressed(MouseEvent e) {
    button.setBorder(BorderFactory.createLoweredBevelBorder());
  }

  public void mouseReleased(MouseEvent e) {
    button.setBorder(null);
  }
});
Dan D.
  • 32,246
  • 5
  • 63
  • 79
  • It's so simple that now I'm ashamed that I didn't think about it by myself. But it solves half of my problem - to be more specific "pressed/clicked" one. Do you know maybe how can I do it with "selected" state? (I probably should mention at start that this state concerns JToggleButton) Thanks in advance for your help. – Ancient Behemoth Sep 06 '12 at 09:19
  • 1
    OK I found this one myself already. If someone would like to know here's the answer: `public void paintComponent(Graphics g) { super.paintComponent(g); if (isSelected()) { setBorder(BorderFactory.createLoweredBevelBorder()); } else { setBorder(null); } }` But thanks for your help **Dan**, you helped me a lot! – Ancient Behemoth Sep 06 '12 at 09:43
  • @AncientBehemoth Thanks for the setBorder(null) for removing the Bevel border. – Kenny Dabiri Jun 05 '20 at 05:05
2

Have look at ButtonModel for JButtons JComponents, there are implemented all your requierements

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319