允许用户仅在DatePicker中选择星期一

时间:2016-04-03 22:27:13

标签: javafx datepicker

我正在开发一个javafx项目,并且我已经包含了一个DatePicker。我想让用户只能选择星期一

DatePicker startDate = new DatePicker();

任何想法,如果可能的话?

1 个答案:

答案 0 :(得分:2)

您需要做两件事:

  1. 如果用户将文本字段中的日期更改为非星期一的日期,则返回更改。您可以使用DatePicker。{/ li>的converter property执行此操作
  2. 禁用弹出窗口中不是星期一的所有单元格。您可以使用dayCellFactory
  3. 执行此操作

    简单示例:

    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);
        }
    }