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

被折叠的 条评论
为什么被折叠?



