P
P
P_Alexander2016-09-23 17:53:04
Java
P_Alexander, 2016-09-23 17:53:04

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

2 answer(s)
S
Sergey Gornostaev, 2016-09-23
@P_Alexander

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");
    }
}

E
Evgeny Kornachev, 2016-09-23
@zelan

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();
            }
        };

this listener should be added to each button and it should describe what needs to be done depending on the id.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question