Text Field Auto Tab
Posted by Rob Camick on October 25, 2009
Anybody who has ever written a DocumentFilter has probably seen the DocumentSizeFilter example from the Swing tutorial on “Implementing a DocumentFilter”. It is simple, straight forward and works well. However, wouldn’t it be nice to have some additional functionality, namely the ability for auto tabbing when the Document is full?
Actually, I’m a little suprised that auto tabbing is not a property of a JTextField. Implementing auto tabbing functionality in a DocumentFilter is not as staight forward as you might expect. Remember, a Document can be shared by multiple text components, so the main problem is finding the focusable text component that is updating the Document.
The SizeDocumentFilter improves upon the DocumentSizeFilter by adding auto tabbing support. A SizeDocumentFilter can be used in two ways depending on how the size is specified:
- fixed size – a size is specified when the filter is created. The filter can be added to any number of text components, and the Document size will be the same for all Documents
- variable size – a size of 0 is specified when the filter is created. This can only be used when adding the filter to JTextFields. In this case the size of the Document is determined by invoking the getColumns() method of the text field. Therefore the filter can be used by multiple text fields with each Document size being different.
The code to create a variable sized filter would be something like:
JTextField tf1 = new JTextField(3);
JTextField tf2 = new JTextField(4);
SizeDocumentFilter sf = new SizeDocumentFilter();
You can still add the filter directly to the AbstractDocument if you wish, I just created the installFilter() method as a convenience method.
AbstractDocument doc = (AbstractDocument)tf1.getDocument();
doc.setDocumentFilter( sf );
Auto tabbing is turned on by default but can be changed by using the setAutoTab(…) method. It is anticipated the SizeDocumentFilter would most commonly be used on a JTextField, although there is no reason it can’t be used on a JTextArea or JTextPane.
Now you have another simple filter for your toolkit. The SizeDocumentFilter can also be used with a ChainedDocumentFilter introduced last week.