change buttons backgroundcolor in awt

冷暖自知 提交于 2019-12-02 01:57:09

have you red the javadoc for JButton?

edit:

Sorry i looked over your code to quickly. What your doing right now is setting the background color of every component in the current container. While your buttons array is global you could simply loop trough that collection again to get the correct components "the buttons" and setting the background color like so:

        for (JButton b : buttons) // line 75, i want this one
           b.setBackground(col); // to change the buttons backgroundcolor
        repaint(); // but it changes the frames backgroundcolor instead

The answer is, no, not really - or at least not as you might expect.

The button's content is provided by the look and feel delegate, most of which ignore things like the background property (or at least don't use it in ways you might think it should).

Instead, you need to remove these decorations and do a little of the work yourself

For example...

buttons = new JButton[10];
for (int i = 0; i < 10; i++) { // 10 Knöpfe im Array
    buttons[i] = new JButton("" + i);
    buttons[i].setFont(new Font("Courier", Font.BOLD, 34));
    buttons[i].setContentAreaFilled(false);
    buttons[i].setOpaque(true);
    buttons[i].setBorder(new EtchedBorder(EtchedBorder.LOWERED));
    buttons[i].setBackground(Color.RED);
    buttons[i].addActionListener(this); // 
}

This disables the area filling, replaces the border and makes the component transparent, which produces something along the lines of

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!