Search code examples
javaswingnetbeansjframejbutton

Changing colour of all buttons in netbeans


I've got 4 Buttons on my Form and a menu bar with an option to change their colours. In my code I change colour of each one individually, like this:

jButton1.setBackground(Color.cyan);
jButton2.setBackground(Color.cyan);
jButton3.setBackground(Color.cyan);
jButton4.setBackground(Color.cyan);

Which isn't a problem right now but might become one if I add more of them. So is there a way to change the colour of all present buttons at once?


Solution

  • You can try to create an array of jbuttons such as:
    JButton[] buttonsArr = new JButton[4];
    and then you can loop on the items and set color of text for all of them. Such as:

    for(int i = 0;i < 4;i++){
    buttonsArr[i] = new JButton(String.valueOf(i));
    // Or you can add the color such as
    buttonsArr[i].setBackground(Color.cyan); 
    }
    

    Another solution is to declare a Color Variable and use it as a global variable or as Enum such as:

    Color globalColor = new Color(187, 157, 177);
    
    jButton1.setBackground(globalColor);
    jButton2.setBackground(globalColor);
    jButton3.setBackground(globalColor);
    jButton4.setBackground(globalColor);
    

    And whenever you need to change it you can change it easily by changing it is value.

    Check those links for more help:
    Link_1 & Link_2