Last active
September 2, 2019 05:33
-
-
Save abhinayagarwal/2ce9584d2121082bd67ffb2d59a0853d to your computer and use it in GitHub Desktop.
Creates a TextField which only accepts digits and adds hypen after 3 and 6 digit.
This file contains 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
import javafx.application.Application; | |
import javafx.geometry.Pos; | |
import javafx.scene.Scene; | |
import javafx.scene.control.TextField; | |
import javafx.scene.control.TextFormatter; | |
import javafx.scene.layout.VBox; | |
import javafx.stage.Stage; | |
import javafx.util.StringConverter; | |
public class PhoneNumberTextFieldSample extends Application { | |
public void start(Stage stage) { | |
final TextField textField = new TextField(); | |
final StringConverter<String> stringConverter = new StringConverter<>() { | |
@Override | |
public String toString(String object) { | |
if (object.length() > 6) { | |
return object.substring(0, 3) + "-" + object.substring(3, 6) + "-" + object.substring(6); | |
} else if (object.length() > 3) { | |
return object.substring(0, 3) + "-" + object.substring(3); | |
} | |
return object; | |
} | |
@Override | |
public String fromString(String string) { | |
return string == null ? null : string.replace("-", ""); | |
} | |
}; | |
textField.setTextFormatter(new TextFormatter<>(stringConverter, "", change -> { | |
if (change.getText().chars().allMatch(Character::isDigit)) { | |
return change; | |
} | |
return null; | |
})); | |
VBox root = new VBox(30, textField); | |
root.setAlignment(Pos.CENTER); | |
Scene scene = new Scene(root, 640, 480); | |
stage.setScene(scene); | |
stage.show(); | |
} | |
public static void main(String[] args) { | |
launch(args); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment