Re: Inline Listeners
On 11.06.2007 16:25, Jason Cavett wrote:
I am added listeners (DocumentListener) to a GUI component
(specifically a class that extends JTextField). I am wondernig why
listeners can be instantiated WITHOUT knowing any of the information
within the listener. For example...
nameTextField.getDocument().addDocumentListener(
new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
if (fireEvent) {
update();
}
}
public void insertUpdate(DocumentEvent e) {
if (fireEvent) {
update();
}
}
public void removeUpdate(DocumentEvent e) {
if (fireEvent) {
update();
}
}
private void update() {
dataModel.setName(nameTextField.getText());
commonUpdate();
nameTextField.verify();
}
});
This listener is added when the GUI is instantiated, however, it is
not until later that I set the dataModel. Why does this work? (I
realize this is probably a fundamental question, but since I never
understood it fully, I figured I would ask.)
Your anonymous class inherits a reference to the instance of the
surrounding class. Your method commonUpdate() are invoked on that
instance; same for fields ("nameTextField" in this case).
Kind regards
robert