How can I find out which button was clicked?

Makenshi picture Makenshi · Sep 22, 2011 · Viewed 55.6k times · Source

I've got my buttons working right, and I'm a listener to each button like this:

for(int i = 0; i <= 25; ++i) {
    buttons[i] = new Button(Character.toString(letters[i]));
    buttons[i].addActionListener(actionListener);
    panel1.add(buttons[i]);
}

Here as you can see the listener is called, and I want to find out which button I'm clicking. Is there a way to do that?

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getSource());
    }
};

I need some way to find the button in the array.

Answer

Pratik picture Pratik · Sep 22, 2011

try this

ActionListener actionListener = new ActionListener() {
    public void actionPerformed(ActionEvent actionEvent) {
        System.out.println(actionEvent.getActionCommand());
    }
};