Java 如何知道actionevent是由button还是textfield在运行时生成的?
如何知道actionevent是在运行时由button还是textfield生成的?用于检查触发事件的组件Java 如何知道actionevent是由button还是textfield在运行时生成的?,java,swing,Java,Swing,如何知道actionevent是在运行时由button还是textfield生成的?用于检查触发事件的组件 final JButton b = new JButton("Button"); final JTextField f = new JTextField("TextField"); ActionListener l = new ActionListener() { @Override public void actionPerformed(ActionEvent e)
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);
还可以使用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"); JButton按钮=新JButton(“按钮”); JTextField=newjtextfield(“TextField”); ActionListener=新建ActionListener(){ @凌驾 已执行的公共无效操作(操作事件){ String command=event.getActionCommand(); if(command.equals(“myButton”){ //纽扣 } if(command.equals(“myField”){ //野外工作人员 } } }; addActionListener(listener); setActionCommand(“myButton”); field.addActionListener(listener); field.setActionCommand(“myField”);