【问题标题】:how to set color of Jbutton如何设置Jbutton的颜色
【发布时间】:2011-12-13 08:38:39
【问题描述】:

如何设置 JButton 的颜色?

我试过这个:

button.setBackground(Color.red);

但没有成功。这只是改变按钮边框的颜色。 然后我尝试覆盖paintComponents

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

但现在我看不到 JButton 上的文字

【问题讨论】:

    标签: java swing jbutton


    【解决方案1】:

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

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

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

    【讨论】:

      【解决方案2】:

      为按钮着色的最佳方法是使用 ImageIcons 而不是文本。 您可以使用Gimp 来设计它们。

      确保背景是透明的

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

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

      这是一个启用的按钮,没有按下:

      这是一个按下的启用按钮:

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

      【讨论】:

      • 是的,我也尝试过,但是当我使用整个按钮的图标时,按下按钮时没有图形动作(颜色有所变化)。
      • 这里的小技巧是你应该让图像的背景透明。
      • +1 但我不知道 Gimp 与它有什么关系。您可以在运行时用大约 5 行代码生成纯色图像。
      • 我只是用 Gimp 制作我的 png。 :-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-22
      • 1970-01-01
      • 2011-01-06
      • 2014-06-23
      • 2022-01-22
      • 1970-01-01
      • 2017-04-05
      相关资源
      最近更新 更多