[英]add listener for javafx textField upto 2 decimal place
我想將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]", ""));
}
}
});
在上面的代碼中,什么是極限值的替換(最多兩位小數)。 還是有其他解決方案來限制textField。 我有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);
}
}
我無法抗拒。 以上是兩行的答案(完成所有工作的答案)
private static TextFormatter<Double> new3DecimalFormatter(){
Pattern decimalPattern = Pattern.compile("-?\\d*(\\.\\d{0,3})?");
return new TextFormatter<>(c -> (decimalPattern.matcher(c.getControlNewText()).matches()) ? c : null );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.