Last active
May 12, 2018 16:03
-
-
Save jmebia/50b17181430231f4d25ecfdbe3b23d72 to your computer and use it in GitHub Desktop.
This is a class for managing input checking/restriction on JavaFX TextFields.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // <just add your project's package name here if necessary> | |
| import javafx.scene.control.TextField; | |
| // input manager for JavaFX TextFields | |
| public class TextFieldManager { | |
| // limits text input | |
| public static void addTextLimit (TextField textField, int limit) { | |
| // fired by every text property change | |
| textField.textProperty().addListener((observable, oldValue, newValue) -> { | |
| if(newValue.length() > limit) { | |
| System.out.println("Text length limit exceeded!"); | |
| textField.setText(oldValue); | |
| } | |
| }); | |
| } | |
| // makes the text field accept only numeric values | |
| public static void addNumericInputOnly (TextField textField) { | |
| textField.textProperty().addListener((observable, oldValue, newValue) -> { | |
| if (!newValue.matches("\\d*")) { | |
| textField.setText(newValue.replaceAll("[^\\d]", "")); | |
| } | |
| }); | |
| } | |
| // makes the text field restrict numeric values | |
| public static void restrictNumericInput (TextField textField) { | |
| textField.textProperty().addListener((observable, oldValue, newValue) -> { | |
| textField.setText(newValue.replaceAll("\\d", "")); | |
| }); | |
| } | |
| // makes the text field listen only to | |
| public static void addLetterInputOnly(TextField textField) { | |
| textField.textProperty().addListener((observable, oldValue, newValue) -> { | |
| textField.setText(newValue.replaceAll("[\\W\\d]","")); | |
| }); | |
| } | |
| // restrict characters given by user through an array | |
| public static void restrictSpecificCharacters(TextField textField, char[] restrictedChararcters) { | |
| textField.textProperty().addListener((observable, oldValue, newValue) -> { | |
| String regex = ""; | |
| for (char w : restrictedChararcters) { | |
| regex += w; | |
| } | |
| textField.setText(newValue.replaceAll("["+regex+"]", "")); | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment