JDK-8101931 : Add method to filter text added to a TextField
  • Type: Enhancement
  • Component: javafx
  • Sub-Component: controls
  • Affected Version: fx2.1
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • Submitted: 2012-02-02
  • Updated: 2015-06-16
  • Resolved: 2012-02-02
Related Reports
Duplicate :  
Duplicate :  
Relates :  
Description
In attempting to write a number of text-based controls for samples or tutorials, I'm always blocked by the fact the there is no good way to filter or restrict the input of a TextField. Although we have a FormattedTextField slated for 2.2 (which, by the way, I do not think we should do as a separate control but actually just add the format / mask to TextField or TextInputControl), I may want to do some very custom text input customization that a Format / mask just wouldn't work for (maybe it is context sensitive).

At first I wished that TextField had a protected constructor taking a Content -- that way I could just subclass TextField and produce my own Content restricting the text as I saw fit. However this also means exposing the TextField's TextFieldContent as something that can be overridden, which I'd prefer not to do.

My next thought was to add a filterInput(int index, String text) method which would be called by TextFieldContent.insert. However this doesn't help restrict deletions which also needs to be done.

So maybe we can just add an "accept" method which takes the new proposed string (whether the result of adding text or removing text) and then it returns true or false.

The problem is I want to avoid letting somebody type the incorrect key and the string of the text field being incorrect for a moment and then I change it back to something valid. It would be nicer to restrict the input so it can't go wrong in the first place.
Comments
Blog post showing an example: http://fxexperience.com/2012/02/restricting-input-on-a-textfield/
02-02-2012

Sure enough, simply subclass TextField and override replaceText and replaceSelection. Works beautifully.
02-02-2012

Actually, this may not be an issue. In theory it could be, but as it turns out Content is *only* manipulated by the replaceText and replaceSelection methods on TextInputControl, and I can override these. So I think a mechanism is already in place to do this. If so, I will close the bug as Not an Issue.
02-02-2012