我想将 javaFX 文本字段设置为小数点后两位。我找到了答案,但它是针对数值的。例如
// force the field to be numeric only
textField.textProperty().addListener(new ChangeListener<String>() {
@Override
public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
if (!newValue.matches("\\d*")) {
textField.setText(newValue.replaceAll("[^\\d]", ""));
}
}
});
在上面的代码中,限制值最多两位小数的替换是什么。
或者是否有其他解决方案来限制文本字段。
我有 Binding TextField 这是我的部分代码...
@FXML public TextField InvoiceTotal;
private DoubleProperty invTotal;
invTotal = new SimpleDoubleProperty(0);
netAmount.bind(grossAmount.subtract(disc));
StringConverter<? extends Number> converter= new DoubleStringConverter();
Bindings.bindBidirectional(InvoiceTotal.textProperty(),invTotal,(StringConverter<Number>)converter);
现在我想在 InvoiceTotal 文本字段上设置两位小数限制
在文本字段上使用文本格式化程序。该模式只需匹配任何可能的十进制值,最多两位小数。 (类似于可选的负号,后跟任意数量的数字,然后可选地后跟小数点和 0-2 位数字。)如果生成的文本与该模式匹配,则让文本格式化程序接受更改,否则拒绝它们。
import java.util.function.UnaryOperator;
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.scene.control.TextFormatter.Change;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class DecimalTextField extends Application {
@Override
public void start(Stage primaryStage) {
Pattern decimalPattern = Pattern.compile("-?\\d*(\\.\\d{0,2})?");
UnaryOperator<Change> filter = c -> {
if (decimalPattern.matcher(c.getControlNewText()).matches()) {
return c ;
} else {
return null ;
}
};
TextFormatter<Double> formatter = new TextFormatter<>(filter);
TextField textField = new TextField();
textField.setTextFormatter(formatter);
StackPane root = new StackPane(textField);
root.setPadding(new Insets(24));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)