Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
 }
like image 724
Salar Avatar asked Nov 13 '10 14:11

Salar


People also ask

How can change background color of button in Java?

JButton red = new JButton("RED"); JFrame class is used to create a new JFrame container with the given text as the frame's title. JButton class is used to create button with the given text as content of the button. Color c = new Color(255, 255, 255);

How do I change the color of my swing button?

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

How do I change a button in Java?

By default, we can create a JButton with a text and also can change the text of a JButton by input some text in the text field and click on the button, it will call the actionPerformed() method of ActionListener interface and set an updated text in a button by calling setText(textField.


2 Answers

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);
}
like image 155
Pablo Santa Cruz Avatar answered Oct 22 '22 03:10

Pablo Santa Cruz


Simple:

btn.setBackground(Color.red);

To use RGB values:

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

like image 25
Ali Mohammadi Avatar answered Oct 22 '22 04:10

Ali Mohammadi