You can use a TextFormatter
to filter out invalid operations on the text field. A TextFormatter
has a filter which filters changes to the text field; you can veto any changes by having the filter return null
. The simplest implementation for what you describe would just filter out any changes where the caret position or the anchor for the text field were before the end of the fixed text:
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));
You can experiment with other logic here (for example if you want the user to be able to select the fixed text).
Here is a 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);
}
}
TextFormatter
. – Progress