将javafx textField的侦听器添加到小数点后2位 [英] add listener for javafx textField upto 2 decimal place
问题描述
我想将javaFX文本字段设置为两位小数.我找到了答案,但这是数字值. e-g
I want to set javaFX text field upto two decimal places . I found the answer but it is for numeric value . e-g
// 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]", ""));
}
}
});
在上面的代码中,什么是极限值的替换(最多两位小数). 还是有其他解决方案来限制textField. 我有Binding TextField,这是我的部分代码...
In above code, what is replacement for limit value upto two decimal. Or is there any other solution for limit the textField. I have Binding TextField Here is My partial Code ...
@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文本字段中设置两个小数限制
Now I want to set two decimal limitation on InvoiceTotal textfield
推荐答案
在文本字段上使用文本格式化程序.该模式只需将任何可能的十进制值与最多两个小数位进行匹配. (类似于可选的负号,后跟任意数量的数字,然后可选地后跟小数点和0-2位数字.)如果结果格式的文本与该格式匹配,则让文本格式化程序接受更改,否则拒绝它们.>
Use a text formatter on the text field. The pattern just has to match any possible decimal value with up to two decimal places. (Something like optional negative sign, followed by any number of digits, then optionally followed by a decimal point and 0-2 digits.) Just have the text formatter accept changes if the resulting text matches that pattern, and reject them otherwise.
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);
}
}
这篇关于将javafx textField的侦听器添加到小数点后2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!