Search code examples
javaswingjbuttonjcomponent

How can I run a code for multiple JButtons?


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)));

Solution

  • 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)));
    }