How to set a background color of a JButton in Java?

后端 未结 6 1562
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 19:33

I am developing a Java Desktop Application. In it I have 4 JButtons on a JPanel. Now I want that whenever a button is clicked its background color

6条回答
  •  庸人自扰
    2021-01-18 20:35

    have you looked into the decorator pattern in java you pass a button into a method which decorates it depending on whether the button is the current active one, for example if it hovered over.

    public Jbutton decorateButton(JButton b, boolean isHoveredOver){
        if(isHoveredOver)
            b.setBackground(getContentPane().getBackground().GREEN);
        return b;
    }
    

    you call this method from the MouseEvent or ActionEvent methods and just issue a repaint() after. put all your buttons into an array or vector and loop through it passing each one in to the decorateButton method and give the initail boolean value of false then on event set it to true. This way the initial value is default and the button is then decorated upon action the buttons will appear to be acting as part of a group

提交回复
热议问题