1

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.
    }
}
Steve Kuo
  • 61,876
  • 75
  • 195
  • 257
Chris Collins
  • 89
  • 2
  • 11

1 Answers1

4

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]);
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Ah, this works perfect thanks! And for anyone else reading, to find a unique ID, inside the roomListener, add 'int id = event.getSource().hashCode()'.. Im assuming from there we can use a switch case to give the right logic to act based on the button pressed. – Chris Collins Jul 11 '15 at 23:09