您可以爲您的所有組件設置一個偵聽器。
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, ...
),那麼你的每一個聽者類型的一個實例,並將其應用到相應的組件。