【问题标题】:How to disable text selection in TextArea (JavaFX)?如何禁用 TextArea (JavaFX) 中的文本选择?
【发布时间】:2020-08-23 04:36:57
【问题描述】:

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

【问题讨论】:

    标签: javafx textarea textselection


    【解决方案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);
        }
    
    }
    

    【讨论】:

    • 谢谢。这会禁用文本选择突出显示,但是当我将鼠标移到光标上时,光标仍然看起来像文本选择光标。有没有办法安排呢?
    • @chaim770 我认为您可以使用 CSS 更改光标,就像任何其他控件一样,或者只是做textArea.setCursor(Cursor.DEFAULT);
    • 使用 CSS:你必须将光标设置在文本区域的内容上,即.text-area .content { -fx-cursor: default ; }。不过,我可能不建议将其作为良好的用户体验,因为文本光标会提示用户可以在文本区域中键入,而不是提示他们可以选择文本。
    猜你喜欢
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    相关资源
    最近更新 更多