我正在开发一个javafx项目,并且我已经包含了一个DatePicker。我想让用户只能选择星期一
DatePicker startDate = new DatePicker();
任何想法,如果可能的话?
答案 0 :(得分:2)
您需要做两件事:
DatePicker
。{/ li>的converter
property执行此操作
dayCellFactory
。简单示例:
import java.time.DayOfWeek;
import java.time.LocalDate;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.DateCell;
import javafx.scene.control.DatePicker;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.StringConverter;
public class DatePickerMondaysOnly extends Application {
@Override
public void start(Stage primaryStage) {
DatePicker datePicker = new DatePicker();
StringConverter<LocalDate> defaultConverter = datePicker.getConverter();
datePicker.setConverter(new StringConverter<LocalDate>() {
@Override
public String toString(LocalDate object) {
return defaultConverter.toString(object);
}
@Override
public LocalDate fromString(String string) {
LocalDate date = defaultConverter.fromString(string);
if (date.getDayOfWeek() == DayOfWeek.MONDAY) {
return date ;
} else {
// not a Monday. Revert to previous value.
// You could also, e.g., return the closest Monday here.
return datePicker.getValue();
}
}
});
datePicker.setDayCellFactory(dp -> new DateCell() {
@Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
setDisable(empty || item.getDayOfWeek() != DayOfWeek.MONDAY);
}
});
// Just for debugging: make sure we only see Mondays:
datePicker.valueProperty().addListener((obs, oldDate, newDate) -> {
if (newDate.getDayOfWeek() != DayOfWeek.MONDAY) {
System.out.println("WARNING: date chosen was not a Monday");
}
System.out.println(newDate + " (" + newDate.getDayOfWeek()+")");
});
StackPane root = new StackPane(datePicker);
root.setPadding(new Insets(20));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}