'Javafx indexOutOfBoundsException within Textfield due to caret Postion
I'm building a small app where TextField text is updated or deleted via buttons on screen. I have utilised code from this post to be able to move the caret around and add text. I can add and delete characters within the TextField however when n amount of characters are added to the TextField then n amount are removed an IndexOutOfBoundsException occurs when you attempt to add another character as the caret position (when all characters are removed) becomes 1 when it should be 0. I do not know why it becomes 1 when it should be 0. What have I done wrong here?
import java.util.concurrent.atomic.AtomicInteger;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Pane panel = new Pane();
VBox box = new VBox();
TextField tf = new TextField();
Button characterButton = new Button("a");
Button deleteChar = new Button("delete");
box.getChildren().addAll(tf, characterButton, deleteChar );
panel.getChildren().add(box);
root.getChildren().add(panel);
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
//handle caret pos
AtomicInteger caretPos = new AtomicInteger();
tf.caretPositionProperty().addListener((obs, oldVal, newVal) -> {
System.out.println("newval" + newVal);
if (tf.isFocused()) {
caretPos.set(newVal.intValue());
System.out.println("Innernewval" + newVal);
}
});
//add character
characterButton.setOnAction(( event) -> {
Button btn = (Button)event.getSource();
System.out.println("Pressed " + btn.getText() + " button");
int pos = caretPos.get();
tf.insertText(pos, btn.getText());
tf.requestFocus();
tf.positionCaret(pos+1);
System.out.println("caretPos on add: " + caretPos.get());
});
//remove character
deleteChar.setOnAction(( event) -> {
Button btn = (Button)event.getSource();
System.out.println("Pressed " + btn.getText() + " button");
int newCaretPos = caretPos.get()-1;
tf.deleteText(newCaretPos, caretPos.get());
tf.requestFocus();
tf.positionCaret(newCaretPos);
System.out.println("caretPos on delete: " + caretPos.get());
});
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
