在JavaFX文本字段中的输入文本之前显示不可删除的文本

Mat*_*det 3 java shell javafx caret textfield

我目前正在尝试构建行为类似于命令外壳的应用程序。我想在javaFX文本字段中的用户输入文本之前显示我给它的路径(或至少一个'>'字符)。像这样:

在此处输入图片说明

我有它,以便在用户提交文本时清除文本字段。提交后,它将字段的文本设置为我的路径,以达到类似的效果,但是用户仍然可以在输入文本时删除该路径。

如何使路径文本显示在字段中,但用户无法删除它?

我已经尝试过了,但是提交后它只会更新插入符号的位置:

        textField.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            textField.positionCaret(textField.getLength());
        }
    });
Run Code Online (Sandbox Code Playgroud)

Jam*_*s_D 5

您可以使用a TextFormatter过滤掉文本字段上的无效操作。A TextFormatter有一个过滤器,用于过滤对文本字段的更改;您可以通过返回过滤器来否决任何更改null。对于您所描述的内容,最简单的实现只是过滤掉文本字段的插入标记位置或锚点在固定文本结尾之前的所有更改:

UnaryOperator<TextFormatter.Change> filter = c -> {
    if (c.getCaretPosition() < prefix.length() || c.getAnchor() < prefix.length()) {
        return null ;
    } else {
        return c ;
    }
};

textField.setTextFormatter(new TextFormatter<String>(filter));
Run Code Online (Sandbox Code Playgroud)

您可以在此处尝试其他逻辑(例如,如果希望用户能够选择固定文本)。

这是一个SSCCE:

import java.util.function.UnaryOperator;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class TextFieldFixedPrefix extends Application {

    private TextField createFixedPrefixTextField(String prefix) {
        TextField textField = new TextField(prefix);

        UnaryOperator<TextFormatter.Change> filter = c -> {
            if (c.getCaretPosition() < prefix.length() || c.getAnchor() < prefix.length()) {
                return null ;
            } else {
                return c ;
            }
        };

        textField.setTextFormatter(new TextFormatter<String>(filter));

        textField.positionCaret(prefix.length());

        return textField ;
    }

    @Override
    public void start(Stage primaryStage) {

        TextField textField = createFixedPrefixTextField("/home/currentUser $ ");
        StackPane root = new StackPane(textField);
        Scene scene = new Scene(root, 300,40);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
Run Code Online (Sandbox Code Playgroud)