java button 背景色,如何在Java中设置JButton的背景颜色?

在Java桌面应用程序中,开发人员通常需要处理按钮点击事件并改变按钮的视觉状态。本文讨论了如何在点击按钮时更改其背景色为橙色,并重置其他按钮的背景色为默认值。提出了使用null来恢复默认颜色的建议,以及考虑使用JToggleButton和ButtonGroup实现类似单选按钮的效果,通过设置选中和未选中时的图标来改变视觉反馈,而不是修改背景色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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.

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. How can I get the default background color?

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

解决方案

just use null to use the default color:

button1.setBackground(Color.ORANGE);

button2.setBackground(null);

...

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

...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值