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

后端 未结 7 1079
名媛妹妹
名媛妹妹 2020-12-06 00:30

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

相关标签:
7条回答
  • 2020-12-06 01:05

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

    0 讨论(0)
  • 2020-12-06 01:08

    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.

    0 讨论(0)
  • 2020-12-06 01:11

    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

    0 讨论(0)
  • 2020-12-06 01:13

    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.

    0 讨论(0)
  • 2020-12-06 01:16
    for(int i=1;i<=9;i++) {
        p3.add(new JButton(""+i) {{
            // initialize the JButton directly
            setBackground(Color.BLACK);
            setForeground(Color.GRAY);
        }});
    }
    
    0 讨论(0)
  • 2020-12-06 01:17

    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);
    }
    
    0 讨论(0)
提交回复
热议问题