Created
September 11, 2015 15:10
-
-
Save karimsqualli96/f8d4c2995da8e11496ed to your computer and use it in GitHub Desktop.
A Simple Javafx TextField Using TextFormatter To Allow Only Double Value
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
| /* | |
| * 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(); | |
| } | |
| } |
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
Regarding line 46:
Should one escape the
.character so that it matches a literal.character and not use it as it's special meaning? That is: