Advertisement
Guest User

Untitled

a guest
May 24th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. package model;
  2.  
  3. import javafx.application.Platform;
  4. import javafx.scene.control.TextField;
  5. import javafx.scene.input.KeyCode;
  6.  
  7. public class PhoneField extends TextField {
  8.  
  9. private Runnable placeCursorAtEnd, clearLater;
  10.  
  11. public PhoneField() {
  12. super();
  13. }
  14.  
  15. public PhoneField(long text) {
  16. super();
  17. setText(String.valueOf(text));
  18. }
  19.  
  20. {
  21. placeCursorAtEnd = () -> end();
  22. clearLater = () -> clear();
  23. init();
  24. }
  25.  
  26. private void init() {
  27. textProperty().addListener((v, oldVal, newVal) -> {
  28. if (newVal.endsWith("-"))
  29. return;
  30.  
  31. if (newVal.isEmpty())
  32. return;
  33.  
  34. if (newVal.equals("("))
  35. Platform.runLater(clearLater);
  36.  
  37. newVal = normalize(newVal);
  38.  
  39. if (newVal.length() < 3) {
  40. setText("(" + newVal);
  41. } else if (newVal.length() == 3) {
  42. setText("(" + newVal + ")");
  43. } else if (newVal.length() <= 6) {
  44. setText("(" + newVal.substring(0, 3) + ")" + newVal.substring(3));
  45. } else if (newVal.length() > 6 && newVal.length() <= 10) {
  46. setText("(" + newVal.substring(0, 3) + ")" + newVal.substring(3, 6) + "-" + newVal.substring(6));
  47. } else {
  48. setText(newVal.substring(0, 10));
  49. }
  50. Platform.runLater(placeCursorAtEnd); // Places cursor at the end
  51. });
  52. setOnKeyPressed(e -> {
  53. if (e.getCode() == KeyCode.BACK_SPACE) {
  54. if (getText().endsWith(")")) {
  55. setText(getText().substring(0, 3));
  56. }
  57. }
  58. });
  59. setOnKeyReleased(e -> {
  60. if (getText().endsWith("-")) {
  61. setText(normalize(getText()).substring(0, 6));
  62. }
  63. });
  64. }
  65.  
  66. private String normalize(String s) {
  67. String toReturn = "";
  68. for (int i = 0; i < s.length(); i++) {
  69. if (Character.isDigit(s.charAt(i))) {
  70. toReturn += s.charAt(i);
  71. }
  72. }
  73. return toReturn.replaceAll("\\)", "").replaceAll("\\(", "").replaceAll("-", "");
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement