如何设置Jbutton的颜色

时间:2011-10-22 22:13:28

标签: java swing 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上的文字

2 个答案:

答案 0 :(得分: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张图片。

答案 1 :(得分:3)

背景颜色的影响取决于您的外观和感觉。见http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/index.html

您应该选择以您想要的方式使用背景颜色的外观。我不知道你现在在用什么。如果你有默认的LAF设置,颜色和删除边框就足够了:

button.setBackground(color);
button.setBorder(null);