Search code examples
javaswingjbutton

Apply common code to group of jbuttons


Is it possible to apply a common code to multiple jbuttons in a frame on click of any jbutton. Its like when I click, say jbutton80, then:

from jbutton1 to jbutton75

{

// common code that applies to all jbutton in loop

}

I am making quiz app in java and have around 70-80 buttons in jframe. Each button corresponds to a question. Questions are divided in sections. So I want:

//if user selects(or clicks on jbutton) section a setvisible(true) from jbutton1 to jbutton20 and setvisible(false) from jbutton21 to jbutton 80.

Sorry, if this question has been asked before. I tried to search any relevant post but couldn't find one.


Solution

  • Did you try making an action listener

    ActionListener l = new ActionListener() { /* code here */ };
    

    And then adding the same one to all of the JButtons?

    for (JButton b : buttons) {
         b.addActionListener(l);
    }