I want to disable the user's ability to select text in textArea of JavaFX. How can this be done?
Asked
Active
Viewed 736 times
1 Answers
1
This is perhaps a little counter-intuitive, but the way to do this is to use a TextFormatter
. The Change
passed to a text formatter includes the current caret position and anchor position (and the any changes to either result in a change being forwarded to, and possibly vetoed or modified by, the text formatter). By setting the anchor so that it is the same as the caret position, you ensure nothing is selected:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class DisableTextSelection extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
TextArea textArea = new TextArea();
textArea.setTextFormatter(new TextFormatter<String>(change -> {
change.setAnchor(change.getCaretPosition());
return change ;
}));
BorderPane root = new BorderPane(textArea);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}

James_D
- 201,275
- 16
- 291
- 322
-
Thank you. This disables the text selection highlight, but still the cursor looks like a text selection cursor when I move my mouse over it. Is there a way to arrange that too? – chaim770 May 07 '20 at 19:33
-
@chaim770 I think you can change the cursor with CSS, just the same as any other control, or just do `textArea.setCursor(Cursor.DEFAULT);`. – James_D May 07 '20 at 19:34
-
1Use CSS: you have to set the cursor on the text area's content, i.e. `.text-area .content { -fx-cursor: default ; }`. I probably wouldn't recommend this as a good user experience, though, because the text cursor gives a hint that the user can type in the text area, not so much a hint that they can select text. – James_D May 07 '20 at 19:50