I’m trying to create a Spinner in JavaFX that accepts only multiples of 0.25 and has positive and negative masks, such as -1,50 and +1,50. In both cases, I need the mask to show (-) and (+). The TextField field must be editable and follow the same rule.
I managed to create a customizable TextField like this but i dont know how to do in a Spinner:
public class TestPane extends BorderPane {
public TestPane() {
TextField textField = new TextField();
BigDecimalConverter converter = new BigDecimalConverter();
TextFormatter<BigDecimal> textFormatter = new TextFormatter<>(converter, BigDecimal.ZERO, c -> {
if (!c.getControl().isFocused()) return null;
String newText = c.getControlNewText().replace(".", ",");
if (c.getControlNewText().isEmpty()) {
return c;
}
if (c.getControlNewText().equals("-") && c.getAnchor() == 1) {
return c;
}
if (c.getControlNewText().equals("+") && c.getAnchor() == 1) {
return c;
}
if (c.getControlNewText().startsWith("-") && c.getControlCaretPosition() == 0) {
return c;
}
if (c.getControlNewText().startsWith("+") && c.getControlCaretPosition() == 0) {
c.setText(c.getText() + " ");
return c;
}
BigDecimal newValue = converter.fromString(c.getControlNewText());
if (newValue != null) {
return c;
} else {
return null;
}
});
textFormatter.valueProperty().bindBidirectional(valueProperty);
textField.setTextFormatter(textFormatter);
setCenter(new VBox(10, new HBox(6, new Text("TextField 1"), textField)));
}
}
public static class BigDecimalConverter extends BigDecimalStringConverter {
@Override
public String toString(BigDecimal value) {
if (value == null) return "0";
return super.toString(value);
}
@Override
public BigDecimal fromString(String value) {
if (value == null || value.isEmpty()) return BigDecimal.ZERO;
return super.fromString(value);
}
}
New contributor
Gustavo Perinazzo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.