如何知道actionevent是否是在运行时按钮或文本字段生成的?
答案 0 :(得分:2)
使用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 :(得分:1)
还可以使用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");