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

Salar picture Salar · Nov 13, 2010 · Viewed 199k times · Source

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));
 }

Answer

Pablo Santa Cruz picture Pablo Santa Cruz · Nov 13, 2010

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);
}