Search code examples
javaswinguser-interfacejbuttonactionlistener

Java: Creating multiple (duplicate) buttons that perform the same action but to themselves


BACKGROUND INFO: I want to make a 9x9 grid of buttons that act as empty beds. All buttons say "Add bed" and when clicked open up a window to write data about the occupant. Once saved the button will change to an occupied bed image.

QUESTION: Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+

CODE:

    //button1 (inside the gui function)
    addBed1 = new JButton("Add bed"); //button 1 of 9
    addBed1.addActionListener(new room1Listener());

class room1Listener implements ActionListener{
    public void actionPerformed(ActionEvent event){
        addBed1.setText("Adding bed..);
        addBedGui(); //Generic window for adding bed info.
    }
}

Solution

  • Is it possible to create an event listener that does the same thing for each button, but applies it to the button being pressed? Im new to java but I understand that good code should be able to do this in a few lines rather than 100+

    Absolutely. In fact you can create one ActionListener object and add this same listener to each and every button in a for loop. The ActionListener will be able to get a reference to the button that pressed it via the ActionEvent#getSource() method, or you can get the JButton's actionCommand String (usually its text) via the ActionEvent#getActionCommand() method.

    e.g.,

    // RoomListener, not roomListener
    class RoomListener implements ActionListener{
        public void actionPerformed(ActionEvent event){
            AbstractButton btn = (AbstractButton) event.getSource();
            btn.setText("Adding bed..);
            addBedGui(); //Generic window for adding bed info.
        }
    }
    

    and

    RoomListener roomListener = new RoomListener();
    JButton[] addButtons = new JButton[ADD_BUTTON_COUNT];
    for (int i = 0; i < addButtons.length; i++) {
       addButtons[i] = new JButton("     Add Bed     "); // make text big
       addButtons[i].addActionListener(roomListener);
       addBedPanel.add(addButtons[i]);
    }