TextField Document model

Scott Palmer swpalmer at gmail.com
Wed Oct 17 11:05:31 PDT 2012


The JavaFX TextField drops the DocumentModel (which generally just gets in the way for a simple one line text field) and just does what it is supposed to.
All of the properties like caretPosition and selection are as they should be, and using an event filter you can easily deal with things like making a control that forces everything to uppercase.

If you want to insert a String (in this case at the caret position):

String text = textField.getText();
int pos = textField.getCaretPosition();
String newString = text.subString(0,pos) + insertedText + text.substring(pos, text.length());
textField.setText(newString);
textField.positionCaret(pos+insertedText.length());

In other words - very straightforward.  It works simply and as expected.

To limit the number of characters use an event filter and consume Key Typed events if the length is too great.

I think the model used in JavaFX is a great improvement on Swing.  The properties and event model make extending things relatively easy.  There are still some rough edges.. but it is moving in the right direction. More importantly it is moving!  Bugs submitted are reacted to quickly.  Just a couple weeks ago I submitted a bug on a Saturday morning and it was evaluated and assigned within fifteen minutes!  It's so encouraging to see activity on the issues I've reported.

Scott



On 2012-10-17, at 1:07 PM, Mark Claassen <markclaassenx at gmail.com> wrote:

> JTextComponents (like JTextField) has a javax.swing.text.Document model
> that made it pretty easy to create a text field that only allowed a certain
> number of characters in it.  Similarly, it was also easy to make a Document
> model that took all input, but forced characters to upper case.
> 
> @Override
> public void insertString(int offs, String str, AttributeSet a) throws
> BadLocationException {
>     <Do stuff>
> }
> 
> What is there going to be in JavaFX to accomplish the same goals?
> 
> Mark



More information about the openjfx-dev mailing list