1

In messages apps, as you type a counter label on the corner gets updated showing the number of characters being entered. How do I create the same thing in Java?

Ahmadali
  • 15
  • 1
  • 6
  • 1
    Use a [listener](http://stackoverflow.com/questions/30160899/value-change-listener-for-javafxs-textfield) – BackSlash Apr 01 '17 at 19:21
  • I tried adding listener, it worked but it is passing whatever I type in the textfield to the counter label. What I need is to show the number of characters on realtime just like the one which is under this comment box: it is updating the numbers that show "n characters left". – Ahmadali Apr 01 '17 at 19:37
  • Yahoooo! I solved the problem )) – Ahmadali Apr 01 '17 at 20:31
  • 1
    inputText.textProperty().addListener(((observable, oldValue, newValue) -> { int c = (int) newValue.length(); String s = String.valueOf(c); inputWordCounter.setText(s); })); – Ahmadali Apr 01 '17 at 20:31

1 Answers1

1

Retrieve a IntegerBinding from the TextField's text property containing it's length and convert this to a StringBinding in a way that suits your needs. Bind the text property of the output Label to the result:

@Override
public void start(Stage primaryStage) {
    TextField textField = new TextField();
    Label label = new Label();
    label.textProperty().bind(textField.textProperty()
                                       .length()
                                       .asString("Character Count: %d"));
    VBox root = new VBox(label, textField);

    Scene scene = new Scene(root);

    primaryStage.setScene(scene);
    primaryStage.show();
}
fabian
  • 80,457
  • 12
  • 86
  • 114