Skip to content

Instantly share code, notes, and snippets.

@karimsqualli96
Created September 11, 2015 15:10
Show Gist options
  • Select an option

  • Save karimsqualli96/f8d4c2995da8e11496ed to your computer and use it in GitHub Desktop.

Select an option

Save karimsqualli96/f8d4c2995da8e11496ed to your computer and use it in GitHub Desktop.
A Simple Javafx TextField Using TextFormatter To Allow Only Double Value
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package manager;
import java.util.function.UnaryOperator;
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
/**
*
* @author Administrator
*/
public class tata extends Application{
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
System.out.println("test");
HBox root = new HBox();
UnaryOperator<TextFormatter.Change> filter = new UnaryOperator<TextFormatter.Change>() {
@Override
public TextFormatter.Change apply(TextFormatter.Change t) {
if (t.isReplaced())
if(t.getText().matches("[^0-9]"))
t.setText(t.getControlText().substring(t.getRangeStart(), t.getRangeEnd()));
if (t.isAdded()) {
if (t.getControlText().contains(".")) {
if (t.getText().matches("[^0-9]")) {
t.setText("");
}
} else if (t.getText().matches("[^0-9.]")) {
t.setText("");
}
}
return t;
}
};
TextField tfDouble = new TextField();
tfDouble.setTextFormatter(new TextFormatter<>(filter));
root.getChildren().add(tfDouble);
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
}
@brcolow
Copy link

brcolow commented Feb 22, 2016

Regarding line 46:

} else if (t.getText().matches("[^0-9.]")) {

Should one escape the . character so that it matches a literal . character and not use it as it's special meaning? That is:

} else if (t.getText().matches("[^0-9\\.]")) {

@Burtan
Copy link

Burtan commented Aug 19, 2016

You should dynamically get the separator char.

DecimalFormatSymbols decimal = new DecimalFormatSymbols(Locale.getDefault());
String sep = String.valueOf(decimal.getDecimalSeparator());

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