Adam
Adam

Reputation: 37

JavaFX TextField Formatting

Is there a way to have my TextField display a dollar sign at the front of my TextField, but not allow the user to delete it?

Image

I want this display, but the user to have no way of removing the dollar sign

Upvotes: 1

Views: 2101

Answers (1)

James_D
James_D

Reputation: 209684

You can use a TextFormatter that filters out any changes to the text that do not result in something beginning with a $ sign:

TextField purchaseCostField = new TextField("$");
UnaryOperator<TextFormatter.Change> filter = change -> {
    if (change.getControlNewText().startsWith("$")) {
        return change ;
    } else {
        return null ;
    }
};
TextFormatter<String> formatter = new TextFormatter<>(filter);
purchaseCostField.setTextFormatter(formatter);

You could take this further and only allow valid input for a currency, by adding additional logic to the filter.

Upvotes: 2

Related Questions