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?