0

I want to change the look of a JButton when its pressed. Instead of making the background dark gray (default), I want it to be blue. I looked at this post, and saw that it uses JButton.setPressedIcon(Icon image) - Making Image button look pressed/clicked in Swing

I don't want to change the image. I only want to change the background color to non-default value when the button is pressed.

How can I do this ? Is it possible to do it without any overriding or creating a new class ?

Community
  • 1
  • 1
SuperStar
  • 495
  • 2
  • 9
  • 22
  • Given your [other question](http://stackoverflow.com/q/15821549/418556), it might be best to do this with Icons. A button supports various icons and will flip between them given state change. – Andrew Thompson Apr 04 '13 at 23:10

3 Answers3

4

You can override paintButtonPressed() in your custom ButtonUI. A related example is seen here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

Same case, with solution. See link:

http://www.coderanch.com/t/346459/GUI/java/JButton-onClick-change-background-color

CronbachAlpha
  • 355
  • 1
  • 5
  • 14
  • 1
    -1 for such an answer. I need specific stuff. I can find many such links too - https://forums.oracle.com/forums/thread.jspa?threadID=1140547 http://www.java.net/node/666979 – SuperStar Apr 04 '13 at 21:30
  • 1
    @SuperStar Then why don't you? – MadProgrammer Apr 04 '13 at 23:50
  • "-1 for such an answer" just have to ask you, why?!? I only provided you with a link with the same case, it's up to you if you want to use it or not. You don't have to reinvent the wheel every time you are solving the problem of making the car roll. – CronbachAlpha Apr 09 '13 at 09:06
0
public class CustomMetalButtonUI extends MetalButtonUI {
    @Override
    protected Color getSelectColor() {
        return new Color(166, 66, 66); // Color
    }
}

Or...

public class CustomMetalButtonUI extends BasicButtonUI {
    @Override
    protected void paintButtonPressed(Graphics g, AbstractButton b) {
        if (b.isContentAreaFilled()) {
            Dimension size = b.getSize();
            g.setColor(new Color(166, 66, 66)); // Color
            g.fillRect(0, 0, size.width, size.height);
        }
    }
}