SuperStar
SuperStar

Reputation: 495

JButton - set color to be shown when its pressed?

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 ?

Upvotes: 0

Views: 8408

Answers (3)

user13614641
user13614641

Reputation: 1

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);
        }
    }
}

Upvotes: 0

trashgod
trashgod

Reputation: 205775

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

Upvotes: 4

Related Questions