Search code examples
javaswingjbutton

how to set color of Jbutton


How can I set the color of a JButton ?

I have tried this:

button.setBackground(Color.red);

but with no success. This just changes the color of button's border. I then tried to override paintComponents

public void paintComponent(Graphics g) {
   g.setColor(Color.GREEN);
   g.fillRect(0, 0, getSize().width, getSize().height);
}

but now I don't see the text on the JButton


Solution

  • The best way to color your buttons is to use ImageIcons instead of text. You could use Gimp in order to design them.

    Make sure that the background is transparent!

    button.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/myimage.png")));
    

    This is a disabled button.setDisabledIcon(... button:

    enter image description here

    This is an enabled button, not pressed:

    enter image description here

    This is a pressed enabled button:

    enter image description here

    The background color-change after pressing is done by Swing. You need just 2 images for this.