The selectedTextProperty listener of a text field causes error

0

I have a text field with a listener that controls every time I select a part of the text it contains. For example, in the following situation everything works correctly when after selecting the two digits on the left I replace them with a 5:

But when I select the two digits on the right I get an error:

  

Exception in thread "JavaFX Application Thread"   java.lang.StringIndexOutOfBoundsException: String index out of range:   3

The code is this:

import javafx.application.Application;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class SelectedText extends Application {

    @Override
    public void start(Stage primaryStage) {
        TextField campoTexto = new TextField();

        StackPane root = new StackPane();
        root.getChildren().add(campoTexto);

        Scene scene = new Scene(root, 100, 100);

        primaryStage.setScene(scene);
        primaryStage.show();

        campoTexto.selectedTextProperty().addListener((final ObservableValue<? extends String> ov,
                final String selectiónAnterior, final String selecciónActual) -> {
                    System.out.println ("Selección Actual: " + selecciónActual); 
                });
        }

    public static void main(String[] args) {
        launch(args);
    }  
}

How can I solve it?

    
asked by 02.09.2016 в 15:48
source

1 answer

0

This is due to a bug in the JavaFX API, as long as it is not corrected you can use the selectionProperty property to monitor the change in the selection of the text field, in the Listener verify if the selection is valid, you get the selected text using The getSelectedText method.

campoTexto.selectionProperty().addListener((listener) ->  {
    if(!campoTexto.getSelectedText().isEmpty()) {
        System.out.println("sr: " + campoTexto.getSelectedText());
    }
});     
    
answered by 14.10.2016 / 15:43
source