您可以为您的所有组件设置一个侦听器。
ActionListener al = new ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// either do it like this
process(e.getActionCommand());
// or like this to distinguish between the controls
if (e.getSource() == firstElement) processChangeInFirstElement();
else if (e.getSource() == secondElement) processChangeInSecondElement();
// etc
}
}
Component firstElement = new JCheckBox("asdf");
firstElement.addActionListener(al);
Component secondElement = new JTextField();
secondElement.addActionListener(al);
如果你需要有多种类型的听众(ChangeListener, MouseListener, ActionListener, KeyListener, ...
),那么你的每一个听者类型的一个实例,并将其应用到相应的组件。