Answer the question
In order to leave comments, you need to log in
How to process many buttons with one listener?
A lot of buttons are created on the panel by a cycle, these buttons are driven into a collection, these buttons are processed by one inner class that implements the ActionListener interface, that is, one handler processes many buttons.
The question is, how can I distinguish which button is pressed if it is without a name ??
Answer the question
In order to leave comments, you need to log in
The handler receives an event instance whose getSource() method returns the object on which the event occurred.
public class ClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
e.getSource().setText("Clicked");
}
}
ActionListener l = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//кнопка которая была нажата
JButton button = (JButton) e.getSource();
//идентификатор действия - предпочтительно использовать его
//естественно при создании кнопки необходимо установить этот идентификатор
String actionCommand = button.getActionCommand();
//или даже без кнопки можно
String actionCommand1 = e.getActionCommand();
//среднячковый вариант
String name = button.getName();
//крайний и отвратительный вариант
String text = button.getText();
}
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question