1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| package test;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Objects;
import java.util.function.UnaryOperator;
import java.util.logging.Level;
import java.util.logging.Logger;
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;
import javafx.util.StringConverter;
public class Main extends Application {
private static class BigDecimalConverter extends StringConverter<BigDecimal> {
private final NumberFormat formatter = new DecimalFormat("0.0E0");
private BigDecimal lastValidValue;
public BigDecimalConverter(final BigDecimal defaultValue, final int scale) {
Objects.requireNonNull(defaultValue);
if (scale < 0) {
throw new IllegalArgumentException();
}
lastValidValue = defaultValue;
formatter.setRoundingMode(RoundingMode.HALF_UP);
formatter.setMinimumFractionDigits(scale);
}
@Override
public String toString(BigDecimal value) {
System.out.printf("toString(%s)%n", value);
final String result = formatter.format(value);
System.out.println(result);
return result;
}
@Override
public BigDecimal fromString(String value) {
System.out.printf("fromString(%s)%n", value);
BigDecimal result = lastValidValue;
try {
result = new BigDecimal(value);
lastValidValue = result;
} catch (NumberFormatException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(result);
return result;
}
};
@Override
public void start(Stage primaryStage) {
final TextField field = new TextField();
final BigDecimal defaultValue = BigDecimal.ZERO;
final StringConverter<BigDecimal> valueConverter = new BigDecimalConverter(defaultValue, 3);
final UnaryOperator<TextFormatter.Change> filter = (change) -> {
final String text = change.getText();
System.out.printf("FILTER: %s%n", text);
System.out.println(text.isEmpty() || text.matches("[0-9.E+-]+"));
final TextFormatter.Change result = (text.isEmpty() || text.matches("[0-9.E+-]+")) ? change : null;
return result;
};
final TextFormatter<BigDecimal> formatter = new TextFormatter<>(valueConverter, defaultValue, filter);
field.setTextFormatter(formatter);
formatter.valueProperty().addListener((observable, oldValue, newValue) -> System.out.printf("%s -> %s%n", oldValue, newValue));
final StackPane root = new StackPane();
root.getChildren().add(field);
final Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Test");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
} |
Partager