如何在Java中设置JButton的背景颜色? [英] How to set a background color of a JButton in Java?

查看:665
本文介绍了如何在Java中设置JButton的背景颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个Java桌面应用程序。在其中我在 JPanel 上有4 JButtons 。现在我希望每当点击一个按钮时,它的背景颜色会变成其他颜色(比如橙色)来表示它已被点击,所有其他3个按钮的背景颜色重置为默认颜色(如果它们中的任何一个都有橙色)背景颜色。

I am developing a Java Desktop Application. In it I have 4 JButtons on a JPanel. Now I want that whenever a button is clicked its background color changes to some other color (say orange) to represent that it has been clicked and the background color of all other 3 buttons reset to their default color (in case any of them had Orange background color).

因此,一次只有一个按钮可以有橙色。

So, at one time only one button can have the orange color.

当前我已经应用的方法是我已经在JButton的 xxxActionPerformed()方法中实现了以下代码button1

The current approach that I have applied is that I have implemented the following code in the xxxActionPerformed() method of JButton button1

button1.setBackground(Color.Orange);
button2.setBackground(Color.Gray);
button3.setBackground(Color.Gray);
button4.setBackground(Color.Gray);

以及其他三个按钮类似。

and similarly for the rest three buttons.

现在实际上,我不希望背景颜色为灰色(对于未点亮的按钮)。相反,我想要默认的背景颜色,以便背景颜色根据最终用户平台的外观将其自身调整为GUI的外观。

Now in actual, I don't want the backgroud color as Gray (for unclicked button). Instead, I want the default background color so that the backgroud color will adjust itself to the look-and-feel of the GUI according to the end-user's platform's look-and-feel.

Q1。如何获得默认背景颜色?

Q1. How can I get the default background color?

Q2。这是执行此操作的正确方法还是有任何其他机制可以通过该机制将按钮组中的所有四个按钮分组,以便一次只能有一个具有指定的属性(如单选按钮)?

Q2. Is this the correct approach to do this or Is there any other mechanism through which I can group all the four buttons in a button group so that only one can have the specified property at one time (like radio buttons)?

推荐答案


  1. 只需使用 null 即可使用默认值颜色:

  1. just use null to use the default color:

button1.setBackground(Color.ORANGE);
button2.setBackground(null);
...


  • 考虑将JToggleButtons与ButtonGroup一起使用,设置Icon和PressedIcon的按钮。无需更改背景颜色。

  • consider using JToggleButtons with a ButtonGroup, set the Icon and PressedIcon of the buttons. No need to change the background color.

    button1 = new JToggleButton(new ImageIcon("0.jpg"));
    button1.setSelectedIcon(new ImageIcon("1.jpg"));
    button2 = new JToggleButton(new ImageIcon("0.jpg"));
    button2.setSelectedIcon(new ImageIcon("2.jpg"));
    ...
    ButtonGroup group = new ButtonGroup();
    group.add(button1);
    group.add(button2);
    ...
    


  • 这篇关于如何在Java中设置JButton的背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆