Reputation: 13
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?
Upvotes: 1
Views: 1043
Reputation: 305
Assume you have this interface
and you want to change color of all buttons to any other color you want.
My recommendation is to create a recursive method similar to DFS
algorithm that can scan all components in your interface and find all buttons even if each button is a child for another component.
Here is an example:-
private List<Component> getAllButtons(Component[] components) {
List<Component> buttons = new LinkedList();
for (Component component: components) {
if (component instanceof JButton) {
buttons.add(component);
} else {
JComponent jComponent = ((JComponent) component);
buttons.addAll(getAllButtons(jComponent.getComponents()));
}
}
return buttons;
}
This method needs to pass the parents components of the interface and it will scan each component either it's a button or not, if it's a button! it will be added to the list, if not! it will get the children's of this component and scan each one recursively until get all buttons.
Now, to call this method, you should add listeners to Button Color
items. For me, i prefer to create a one action listener for all these items.
private void actionPerformed(java.awt.event.ActionEvent evt) {
String colorName = ((JMenuItem) evt.getSource()).getText();
Color color = null;
if (colorName.equals("red")) {
color = Color.RED;
} else if (colorName.equals("green")) {
color = Color.GREEN;
} else if (colorName.equals("blue")) {
color = Color.BLUE;
} else if (colorName.equals("cyan")) {
color = Color.CYAN;
}
List<Component> buttons = getAllButtons(this.getComponents());
for (Component component : buttons) {
component.setBackground(color);
}
}
Upvotes: -1
Reputation: 975
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
Upvotes: 2