您可以从 DatePickerSkin 中获取 DatePicker 的弹出内容。有关实现,请参阅此演示:
public class DatePickerPopupDemo extends Application {
@Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 400, 400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
DatePickerSkin datePickerSkin = new DatePickerSkin(new DatePicker(LocalDate.now()));
Node popupContent = datePickerSkin.getPopupContent();
root.setCenter(popupContent);
primaryStage.setScene(scene);
primaryStage.show();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
如果不需要顶栏,可以查找并隐藏。
DatePickerSkin datePickerSkin = new DatePickerSkin(new DatePicker(LocalDate.now()));
Node popupContent = datePickerSkin.getPopupContent();
// force a css layout pass to ensure that lookup calls work
popupContent.applyCss();
popupContent.lookup(".month-year-pane").setVisible(false);
root.setCenter(popupContent);
更新:
从 JDK 9 开始,DatePickerSkin 是公共 API 的一部分,不再需要使用封闭的 com.sun.[...] 实现。 (见JavaDoc)
另外,as mentioned in the comments,要获取所选值,您必须访问从中提取皮肤的DatePicker(例如,将其保存为变量)。
DatePicker datePicker = new DatePicker(LocalDate.now());
DatePickerSkin datePickerSkin = new DatePickerSkin(datePicker);
Node popupContent = datePickerSkin.getPopupContent();
//[...]
LocalDate selectedDate = datePicker.getValue();
您还可以通过向关联属性添加ChangeListener 来监听值更改:
datePicker.valueProperty().addListener(new ChangeListener<LocalDate>() {
@Override
public void changed(ObservableValue<? extends LocalDate> observable, LocalDate oldValue, LocalDate newValue) {
System.out.println("New Value: " + newValue);
}
});
//Or using neat lambda
datePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
System.out.println("New Value: " + newValue);
});