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)?
Use the setBackground method to set the background and setForeground to change the colour of your text.
In general, to set the JFrame background color, just call the JFrame setBackground method, like this: jframe. setBackground(Color. RED);
JButton can become transparentIf the value of the opaque property of a JButton is set to false, the background becomes transparent allowing whatever is behind the button to show through. Only the text and the border of the button remain opaque.
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);
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With