JavaFX datepicker - 如何在第二个datepicker对象中更新日期? [英] JavaFX datepicker - how to update date in a second datepicker object?
问题描述
问题:
我在同一个场景中有两个datepicker对象checkIn_date和checkOut_date。
有一种方法可以自动更改第二个datepicker对象中的日期字段吗?
例如:checkIn_date设置为2015-08-10,checkOut_date设置为2015-08-11。如果我在checkIn_date中更改日期字段,即2015-08-22,则checkOut_date会自动更新为2015-08-23。
感谢您的任何建议。
Problem: I've two datepicker object checkIn_date and checkOut_date in the same scene. There is a way to change automatically the date field in the second datepicker object? For example : checkIn_date is set with 2015-08-10 and checkOut_date is set with 2015-08-11. If I change the date field in checkIn_date i.e. 2015-08-22, checkOut_date update automatically to 2015-08-23. Thanks for any advices.
推荐答案
您可以通过向添加监听器来实现此目的签入DatePicker
,获取新值,添加您想要的天数并将新值更新为签出DatePicker
。
You can achieve this by adding a listener to your check-in DatePicker
, fetch the new value, add the no of days you want to it and update the new value to the check-out DatePicker
.
这是一个MCVE,可以更好地了解我的意思:
Here is a MCVE to give more idea on what I meant :
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
private final int noOfDaysToAdd = 2;
@Override
public void start(Stage primaryStage) throws Exception {
VBox root = new VBox(10);
root.setAlignment(Pos.CENTER);
Label checkInLabel = new Label("Check In : ");
Label checkOutLabel = new Label("Check Out : ");
DatePicker picker1 = new DatePicker();
DatePicker picker2 = new DatePicker();
// Listener for updating the checkout date w.r.t check in date
picker1.valueProperty().addListener((ov, oldValue, newValue) -> {
picker2.setValue(newValue.plusDays(noOfDaysToAdd));
});
HBox checkInBox = new HBox(10, checkInLabel, picker1);
HBox checkOutBox = new HBox(10, checkOutLabel, picker2);
checkInBox.setAlignment(Pos.CENTER);
checkOutBox.setAlignment(Pos.CENTER);
root.getChildren().addAll(checkInBox, checkOutBox);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
输出:
更新
您可以重新编写代码段
picker1.valueProperty().addListener((ov, oldValue, newValue) -> {
picker2.setValue(newValue.plusDays(noOfDaysToAdd));
});
没有lambda为:
picker1.valueProperty().addListener(new ChangeListener<LocalDate>() {
@Override
public void changed(ObservableValue<? extends LocalDate> observable, LocalDate oldValue, LocalDate newValue) {
picker2.setValue(newValue.plusDays(noOfDaysToAdd));
}
});
这篇关于JavaFX datepicker - 如何在第二个datepicker对象中更新日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!