Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package model;
- import javafx.application.Platform;
- import javafx.scene.control.TextField;
- import javafx.scene.input.KeyCode;
- public class PhoneField extends TextField {
- private Runnable placeCursorAtEnd, clearLater;
- public PhoneField() {
- super();
- }
- public PhoneField(long text) {
- super();
- setText(String.valueOf(text));
- }
- {
- placeCursorAtEnd = () -> end();
- clearLater = () -> clear();
- init();
- }
- private void init() {
- textProperty().addListener((v, oldVal, newVal) -> {
- if (newVal.endsWith("-"))
- return;
- if (newVal.isEmpty())
- return;
- if (newVal.equals("("))
- Platform.runLater(clearLater);
- newVal = normalize(newVal);
- if (newVal.length() < 3) {
- setText("(" + newVal);
- } else if (newVal.length() == 3) {
- setText("(" + newVal + ")");
- } else if (newVal.length() <= 6) {
- setText("(" + newVal.substring(0, 3) + ")" + newVal.substring(3));
- } else if (newVal.length() > 6 && newVal.length() <= 10) {
- setText("(" + newVal.substring(0, 3) + ")" + newVal.substring(3, 6) + "-" + newVal.substring(6));
- } else {
- setText(newVal.substring(0, 10));
- }
- Platform.runLater(placeCursorAtEnd); // Places cursor at the end
- });
- setOnKeyPressed(e -> {
- if (e.getCode() == KeyCode.BACK_SPACE) {
- if (getText().endsWith(")")) {
- setText(getText().substring(0, 3));
- }
- }
- });
- setOnKeyReleased(e -> {
- if (getText().endsWith("-")) {
- setText(normalize(getText()).substring(0, 6));
- }
- });
- }
- private String normalize(String s) {
- String toReturn = "";
- for (int i = 0; i < s.length(); i++) {
- if (Character.isDigit(s.charAt(i))) {
- toReturn += s.charAt(i);
- }
- }
- return toReturn.replaceAll("\\)", "").replaceAll("\\(", "").replaceAll("-", "");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement