Salar
Salar

Reputation: 269

How to set background color of a button in Java GUI?

Below is the code which creates 9 buttons in gridlayout form on a specific pannel3. What i want is to make the background of each button black with grey text over it. Can anyone help please?

 for(int i=1;i<=9;i++)
 {
     p3.add(new JButton(""+i));
 }

Upvotes: 21

Views: 271666

Answers (8)

Ash
Ash

Reputation: 11

I tried the previous solutions but still couldn't change the color. Came across another article and solved my problem. The button is made of different layers. Removing all of them helps:

    btn.setOpaque(true);
    btn.setContentAreaFilled(true);
    btn.setBorderPainted(false);
    btn.setFocusPainted(false);
    btn.setBackground(Color.GRAY); // for the background
    btn.setForeground(Color.white); // for the text

Upvotes: 1

luca
luca

Reputation: 7546

Changing the background property might not be enough as the component won't look like a button anymore. You might need to re-implement the paint method as in here to get a better result:

enter image description here

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181460

Check out JButton documentation. Take special attention to setBackground and setForeground methods inherited from JComponent.

Something like:

for(int i=1;i<=9;i++)
{
    JButton btn = new JButton(String.valueOf(i));
    btn.setBackground(Color.BLACK);
    btn.setForeground(Color.GRAY);
    p3.add(btn);
}

Upvotes: 29

Ali Mohammadi
Ali Mohammadi

Reputation: 1324

Simple:

btn.setBackground(Color.red);

To use RGB values:

btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));

Upvotes: 13

GregNash
GregNash

Reputation: 1336

It seems that the setBackground() method doesn't work well on some platforms (I'm using Windows 7). I found this answer to this question helpful. However, I didn't entirely use it to solve my problem. Instead, I decided it'd be much easier and almost as aesthetic to color a panel next to the button.

Upvotes: 2

Tanner
Tanner

Reputation: 1214

You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.

Upvotes: 2

dacwe
dacwe

Reputation: 43504

for(int i=1;i<=9;i++) {
    p3.add(new JButton(""+i) {{
        // initialize the JButton directly
        setBackground(Color.BLACK);
        setForeground(Color.GRAY);
    }});
}

Upvotes: 2

npinti
npinti

Reputation: 52195

Use the setBackground method to set the background and setForeground to change the colour of your text. Note however, that putting grey text over a black background might make your text a bit tough to read.

Upvotes: 1

Related Questions