Java Reference
In-Depth Information
String typeString = null;
if (type.equals(DocumentEvent.EventType.CHANGE)) {
typeString = "Change";
} else if (type.equals(DocumentEvent.EventType.INSERT)) {
typeString = "Insert";
} else if (type.equals(DocumentEvent.EventType.REMOVE)) {
typeString = "Remove";
}
System.out.print("Type : " + typeString + " / ");
Document source = documentEvent.getDocument();
int length = source.getLength();
try {
System.out.println("Contents: " + source.getText(0, length));
} catch (BadLocationException badLocationException) {
System.out.println("Contents: Unknown");
}
}
};
nameTextField.getDocument().addDocumentListener(documentListener);
cityTextField.getDocument().addDocumentListener(documentListener);
Putting It All Together
Now that you've seen the usage of the listeners separately, let's put them all together within
one example. Figure 15-14 shows the end result of this endeavor. Keep in mind that the magic
word to tab out of a component is “Exit.”
Figure 15-14. JTextField event demonstration
The source behind the program in Figure 15-14 is shown in Listing 15-13.
Listing 15-13. Text Event Handling
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class JTextFieldSample {
public static void main(String args[]) {
Runnable runner = new Runnable() {
 
Search WWH ::




Custom Search