【发布时间】:2020-08-23 04:36:57
【问题描述】:
我想禁用用户在 JavaFX 的 textArea 中选择文本的功能。如何做到这一点?
【问题讨论】:
标签: javafx textarea textselection
我想禁用用户在 JavaFX 的 textArea 中选择文本的功能。如何做到这一点?
【问题讨论】:
标签: javafx textarea textselection
这可能有点违反直觉,但这样做的方法是使用TextFormatter。传递给文本格式化程序的Change 包括当前插入符号位置和锚点位置(以及任何更改都会导致更改被转发到文本格式化程序,并可能被文本格式化程序否决或修改)。通过设置锚点使其与插入符号位置相同,您可以确保没有选择任何内容:
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);
}
}
【讨论】:
textArea.setCursor(Cursor.DEFAULT);。
.text-area .content { -fx-cursor: default ; }。不过,我可能不建议将其作为良好的用户体验,因为文本光标会提示用户可以在文本区域中键入,而不是提示他们可以选择文本。