2011-10-22 37 views
5

如何设置JButton的颜色?如何设置Jbutton的颜色

我已经试过这样:

button.setBackground(Color.red); 

,但没有成功。这只是改变了按钮边框的颜色。 我又试图改写paintComponents

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

,但现在我没有看到将JButton

回答

6

而影响了你的按钮,最好的办法是使用ImageIcons而不是文本。 您可以使用Gimp来设计它们。

确保背景是透明的

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

这是一个禁用button.setDisabledIcon(...按钮:

enter image description here

这是一个使能按钮,而不是按压:

enter image description here

这是一个按下启用按钮:

enter image description here

按下后的背景颜色变化由Swing完成。你只需要2张图片。

+0

是啊我也试过,但是当我用整个按钮的图标时,当按下按钮时没有图形动作(颜色的一些变化)。 – hudi

+0

这里的小技巧是你应该使图像的背景透明。 –

+0

+1,但我不知道Gimp与它有什么关系。您可以在运行时在大约5行代码中生成纯色图像。 –