如何禁止在TextArea(JavaFX)中选择文本?

问题描述 投票:0回答:1

我想禁止用户在JavaFX的textArea中选择文本的能力。如何做到这一点?

javafx textarea textselection
1个回答
1
投票

这可能有点违反直觉,但实现的方法是使用 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);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.