JavaFX datepicker - 如何在第二个datepicker对象中更新日期?

Mar*_*arc 1 javafx datepicker

问题:我在同一个场景中有两个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.感谢您的任何建议.

Ita*_*iha 7

您可以通过向您添加侦听器check-in DatePicker,获取新值,添加您想要的天数并将新值更新为您来实现此目的check-out DatePicker.

这是一个MCVE,可以更好地了解我的意思:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

更新

您可以重新编写代码段

picker1.valueProperty().addListener((ov, oldValue, newValue) -> {
    picker2.setValue(newValue.plusDays(noOfDaysToAdd));
});
Run Code Online (Sandbox Code Playgroud)

没有lambda作为:

picker1.valueProperty().addListener(new ChangeListener<LocalDate>() {
    @Override
    public void changed(ObservableValue<? extends LocalDate> observable, LocalDate oldValue, LocalDate newValue) {
        picker2.setValue(newValue.plusDays(noOfDaysToAdd));
    }
});
Run Code Online (Sandbox Code Playgroud)