how to set color of Jbutton

大兔子大兔子 提交于 2019-12-19 03:21:48

问题


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


回答1:


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:

This is an enabled button, not pressed:

This is a pressed enabled button:

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




回答2:


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


来源:https://stackoverflow.com/questions/7862963/how-to-set-color-of-jbutton

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!