Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 264
hudi Avatar asked Oct 22 '11 22:10

hudi


2 Answers

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.

like image 160
Costis Aivalis Avatar answered Oct 02 '22 16:10

Costis Aivalis


What the background color affects depends on your look and feel. See http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/index.html

You should choose a look and feel that uses the background color the way you want. I don't know what you are using at the moment. If you have the default LAF setting the color and removing the border should be enough:

button.setBackground(color);
button.setBorder(null);
like image 35
foowtf Avatar answered Oct 02 '22 15:10

foowtf