Как узнать, был ли actionevent сгенерирован кнопкой или текстовым полем во время выполнения? - PullRequest
0 голосов
/ 13 ноября 2010

Как узнать, было ли сгенерировано actionevent кнопкой или текстовым полем во время выполнения?

Ответы [ 2 ]

2 голосов
/ 13 ноября 2010

Используйте getSource () , чтобы проверить, какой компонент вызвал событие.

final JButton b = new JButton("Button");
final JTextField f = new JTextField("TextField");

ActionListener l = new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == b) {
            /* button fired the event */
        }

        if (e.getSource() == f) {
            /* text field fired the event */
        }
    }
};

b.addActionListener(l);
f.addActionListener(l);
1 голос
/ 13 ноября 2010

Может также использовать actionCommands для различения между ними.

JButton button = new JButton("Button");
JTextField field = new JTextField("TextField");

ActionListener listener = new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {
        String command = event.getActionCommand();
        if (command.equals("myButton") {
            //Button stuff
        }

        if (command.equals("myField") {
            //Field stuff
        }
    }
};

button.addActionListener(listener);
button.setActionCommand("myButton");

field.addActionListener(listener);
field.setActionCommand("myField");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...