Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8088614

[TextField] Possible wrong events order on text change

XMLWordPrintable

      TextField's caret position lags behind the length of the field's content. This means the field's textProperty's InvalidationListener can't rely on the selection and caret position information, because they're invalid at the moment of handling the event.

      Code to reproduce the issue:

      import javafx.application.Application;
      import javafx.beans.InvalidationListener;
      import javafx.beans.Observable;
      import javafx.geometry.Insets;
      import javafx.geometry.Pos;
      import javafx.scene.Scene;
      import javafx.scene.control.Label;
      import javafx.scene.control.TextField;
      import javafx.scene.layout.HBox;
      import javafx.scene.layout.VBox;
      import javafx.stage.Stage;

      public class Test10 extends Application
      {
      public static void main(final String[] args)
      {
      launch(args);
      }

      @Override
      public void start(final Stage primaryStage) throws Exception
      {
      final VBox vbox = new VBox(10);
      vbox.setPadding(new Insets(10));

      final TextField textField = new TextField();
      textField.setPromptText("Type something");
      textField.setMaxWidth(Double.MAX_VALUE);

      final HBox hbox = new HBox(10);
      hbox.setAlignment(Pos.CENTER_LEFT);

      final TextField lengthField = new TextField();
      lengthField.setEditable(false);
      final TextField posField = new TextField();
      posField.setEditable(false);

      hbox.getChildren().addAll(new Label("Text length:"), lengthField, new Label("Cursor position: "), posField);
      vbox.getChildren().addAll(textField, hbox);

      primaryStage.setScene(new Scene(vbox));
      primaryStage.show();

      textField.textProperty().addListener(new InvalidationListener()
      {
      @Override
      public void invalidated(final Observable observable)
      {
      lengthField.setText(Integer.toString(textField.getLength()));
      posField.setText(Integer.toString(textField.getCaretPosition()));
      }
      });
      }
      }

      Type something in the first text field to see what I mean.
      Text length and cursor position values are updated using the InvalidationListener which listens to changes of the textField.textProperty.

            Unassigned Unassigned
            jsmucrjfx Jan Smucr (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            5 Start watching this issue

              Created:
              Updated:
              Imported: