Java Reference
In-Depth Information
Assume the contents of the JTextArea are as follows:
Hello, World
Welcome Home
Adios
The program would report Element objects starting at 0, 0, 13, and 26. The first 0 represents
the start of the content; the second represents the start of the first line.
You'll learn more about Element in Chapter 16.
Filtering Document Models
In the AWT world, if you want to restrict input into a text field—such as to limit input to alpha-
numeric characters or to some numeric range of values—you attach a KeyListener and consume()
keystrokes that you don't want to appear within the component. With the Swing text components,
you could either create a new Document implementation and customize what's accepted in the
Document or attach a DocumentFilter and let it filter input.
While you can certainly create a custom subclass of Document , the more object-oriented
approach is to create a filter, as you don't want to change the Document ; you just want to limit
the input into the model. You then attach the newly created filter to the document by calling
the setDocumentFilter() method of AbstractDocument . Filters work with both PlainDocument
and StyledDocument subclasses.
DocumentFilter is a class, not an interface, so you must create a subclass of that to filter the
text into the document of a text component. If you create a subclass of DocumentFilter , over-
riding these three methods allows you to customize input:
public void insertString(DocumentFilter.FilterBypass fb, int offset, String
string, AttributeSet attributes) : Called when a text string is inserted into the Document .
public void remove(DocumentFilter.FilterBypass fb, int offset, int length) :
Called when something is deleted.
public void replace(DocumentFilter.FilterBypass fb, int offset, int length,
String text, AttributeSet attrs) : Called when something is inserted into the
currently selected text.
To restrict input, just override each method and check to see if the new content would be
valid. If the content would not be valid, reject it.
For example, to create a DocumentFilter subclass to limit to a numeric range, you need to
override the behavior of insertString() , remove() , and replace() . Because you're ensuring
that the input is numeric and within a valid range, you must validate the proposed input to see
if it's acceptable. If it is acceptable, then you can modify the document model by calling the
insertString() , remove() , or replace() method of the DocumentFilter.FilterBypass argument of
each original method call. When the input is unacceptable, you throw a BadLocationException .
Seeing this exception thrown ensures the input method framework understands the user input
was invalid. This will typically trigger the system to beep. Listing 15-7 shows a custom document
filter for limiting an integer range.
Search WWH ::




Custom Search