Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a background color of a JButton in Java?

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

like image 669
Yatendra Avatar asked Jan 18 '10 13:01

Yatendra


People also ask

How do I change the color of a JButton in Java?

Use the setBackground method to set the background and setForeground to change the colour of your text.

How do I change the color of a JFrame in Java?

In general, to set the JFrame background color, just call the JFrame setBackground method, like this: jframe. setBackground(Color. RED);

How do I make a JButton transparent?

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.


1 Answers

  1. just use null to use the default color:

    button1.setBackground(Color.ORANGE);
    button2.setBackground(null);
    ...
    
  2. 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);
    ...
    
like image 125
user85421 Avatar answered Sep 27 '22 22:09

user85421