Skip to content

Instantly share code, notes, and snippets.

@hadinajafi
Last active May 3, 2019 08:04
Show Gist options
  • Select an option

  • Save hadinajafi/c0c2b024790b203bb1417a175e7675fa to your computer and use it in GitHub Desktop.

Select an option

Save hadinajafi/c0c2b024790b203bb1417a175e7675fa to your computer and use it in GitHub Desktop.
Numeral TextField in JavaFX
/** numberfield can be any input field, like spinner, textfield, etc.
/* here numberfield is textfield
/* I commented the necessary imports.
**/
//import java.util.function.UnaryOperator;
//import javafx.scene.control.TextFormatter;
@FXML
private Spinner<Double> balanceField;
//the declaration is out of methods. but the UnaryOperator is in a method like initialize.
public void initialize(URL url, ResourceBundle rb){
UnaryOperator<TextFormatter.Change> filter = change -> {
String newText = change.getControlNewText();
if(newText.matches("([0-9])*[.]([0-9])*"))
return change; //if the regular expression matches the input value.
return null;
};
//setting textformatter to the numberfield
balanceField.getEditor().setTextFormatter(new TextFormatter<>(filter));
}
@hadinajafi
Copy link
Copy Markdown
Author

the ([0-9])*[.]([0-9])* is a regular expression for accepting double numbers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment