title: Control keyboard input into javafx TextField
body: <p>I want to control the input into a Javafx TextField so that I can allow only Numeric input, and so that if the max characters are exceeded, then no change will be made to the textbox.</p>
  
  <p>edit: Based on a recommendation in the comments, I used the method suggested by the JavaFX project lead.  It works great to stop letters from being entered.  I just need it to also filter special characters.  I tried changing the filter to (text.matchs("[0-9]") but that did not allow backspace to be entered.</p>
  
  <p>edit2: Figured out a filter on special chars and length.  Here is my final code.  Thanks for the input fellas.</p>
  
  <p>Here is the TextField class i have created:</p>
  
  <pre><code>import javafx.scene.control.TextField;
  
  public class AttributeTextField extends TextField{
  
      public AttributeTextField() {
          setMinWidth(25);
          setMaxWidth(25);
      }
  
      public void replaceText(int start, int end, String text) {
          String oldValue = getText();
          if (!text.matches("[a-z]") &amp;&amp; !text.matches("[\\\\!\"#$%&amp;()*+,./:;&lt;=&gt;?@\\[\\]^_{|}~]+")) {
              super.replaceText(start, end, text);
          }
          if (getText().length() &gt; 2 ) {
              setText(oldValue);
          }
      }
  
      public void replaceSelection(String text) {
          String oldValue = getText();
          if (!text.matches("[a-z]") &amp;&amp; !text.matches("[\\\\!\"#$%&amp;()*+,./:;&lt;=&gt;?@\\[\\]^_{|}~]+")) {
              super.replaceSelection(text);
          }
          if (getText().length() &gt; 2 ) {
              setText(oldValue);
          }
      }
  }
  </code></pre>
  
  <p>Note:  I have read <a href="https://stackoverflow.com/questions/7555564/what-is-the-recommended-way-to-make-a-numeric-textfield-in-javafx">What is the recommended way to make a numeric TextField in JavaFX?</a> this post, and this solution does not work for me.  It only gets fired after the number has been entered. Meaning someone could type alphabetic text into the box, and it would allow it until they moved focus away from the textfield.  Also, they can enter numbers larger than allowed, but validation happens not on each keypress, but instead after focus shift ('changed' event).</p>