change buttons backgroundcolor in awt

后端 未结 2 629
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 11:24

So i have a GUI program called Safe25. Basically, if you press the buttons in the right order which is \"15032018\" the program closes itself. If you input a correct number, let

相关标签:
2条回答
  • 2021-01-21 11:54

    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
    
    0 讨论(0)
  • 2021-01-21 12:11

    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

    0 讨论(0)
提交回复
热议问题