Reputation: 363
I want run a code for JButtons I want.
I search for this in Internet but I can't find a solution for swing applications.
b1.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b2.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b3.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b4.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b5.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b6.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b7.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b8.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
b9.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
I tried below code but I could not use JButton properties
JButton[] buttons = new JButton[];
I declare it
buttons[0] = b1;
buttons[1] = b2;
buttons[2] = b3;
buttons[3] = b4;
buttons[4] = b5;
buttons[5] = b6;
buttons[6] = b7;
buttons[7] = b8;
buttons[8] = b9;
But this didn't work:
buttons.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
Upvotes: 1
Views: 116
Reputation: 6808
If you do not want to keep the button as fields or in a structure AND the buttons are in one container (if they are in a different container, you will have to do more), another approach would be to use Darryl Burke's SwingUtils class.
So let's see how easier it would be:
for (JButton b : SwingUtils.getDescendantsOfClass(JButton.class, panelWithButtons)) {
b.setFont(new Font("Tahoma",Font.BOLD,14));
}
Voilà! All buttons in "panelWithButtons" JPanel has this font. No fields kept, no array kept.
Upvotes: 0
Reputation: 9437
Step 1: You create an array, and fill it with the buttons.
JButton[] buttons = {b1,b2,b3,b4,b5,b6,b7,b8,b9};
Note: this already fills the array with the buttons, so statements like this:
buttons[0] = b1;
buttons[1] = b2;
buttons[2] = b3;
are redundant.
Step 2: Iterate over the array
for ( JButton button : buttons ) {
// here you are to call the setFont
}
Step 3: Set the font
for ( JButton button : buttons ) {
button.setFont(new Font("Arial", Font.PLAIN, (h / 25)));
}
Upvotes: 2