You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.
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:
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.
for(int i=1;i<=9;i++) {
p3.add(new JButton(""+i) {{
// initialize the JButton directly
setBackground(Color.BLACK);
setForeground(Color.GRAY);
}});
}
Simple:
btn.setBackground(Color.red);
To use RGB values:
btn[i].setBackground(Color.RGBtoHSB(int, int, int, float[]));
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.
Source: Stackoverflow.com