Java Reference
In-Depth Information
In the second text field, the valid range is -100 to +100. Although you can enter any of the
201 numbers into the text field, if you want a negative number, you need to enter something
like 3, left arrow, and minus sign (-). Because the text field validates input with each key, the - by
itself isn't valid. You would need to either specifically accept a - as valid input in the checkInput()
method of the custom DocumentFilter or force users to enter negative numbers in an awkward
manner.
The third text field presents an even more troublesome situation. The valid range of input
is 1000-2000. As you press each key to enter a number, such as 1500, it's rejected. You can't
build up the input to 1500 because, by themselves, 1, 5, and 0 are not valid input. Instead, to
enter a number into this text field, you must enter it somewhere else , place it into the system
clipboard, and then use Ctrl-V to paste it into the text field as the field's final value. You can't
use Backspace to correct a mistake, because no three-digit numbers are valid.
While the IntegerRangeDocumentFilter class shown in Listing 15-7 presents a workable
DocumentFilter for any integer range, it works best with ranges of positive numbers that begin
at zero. If you don't mind seeing the temporarily invalid input in the fields, it may be better to
just attach an InputVerifier to deal with validation when leaving the text field.
DocumentListener and DocumentEvent Interfaces
If you're interested in finding out when the content of a text component changes, you can
attach an implementation of the DocumentListener interface to the Document model of the
component.
public interface DocumentListener implements EventListener {
public void changedUpdate(DocumentEvent documentEvent);
public void insertUpdate(DocumentEvent documentEvent);
public void removeUpdate(DocumentEvent documentEvent);
}
From the three interface methods, you can find out if the contents were added to
( insertUpdate() ), removed ( removeUpdate() ), or stylistically changed ( changedUpdate() ).
Notice that the latter is an attribute change versus a content change.
The interface method will receive an instance of DocumentEvent , from which you can find
out where the change occurred, as well as the type of change, as follows:
public interface DocumentEvent {
public Document getDocument();
public int getLength();
public int getOffset();
public DocumentEvent.EventType getType();
public DocumentEvent.ElementChange getChange(Element element);
}
The offset property of the event is where the change started. The length property of
the event tells the length of the change that happened. The type of the event can be derived
from whichever one of the three DocumentListener methods were called. In addition, the
DocumentEvent.EventType class has three constants— CHANGE , INSERT , and REMOVE —so you
can find out which event type happened directly from the type property.
Search WWH ::




Custom Search