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 a
You may or may not have to use setOpaque method to ensure that the colors show up by passing true to the method.
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.
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);
}});
}
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);
}