将DateTimePicker添加到Button

时间:2016-08-11 14:04:35

标签: java javafx datetimepicker

我正在尝试实现CalendarPicker,以便在我按下JavaFX中的Button时将在新窗口中打开

我为我的日历添加了一些代码:

@FXML
 public void dateTimePicker(Stage primaryStage){
    CalendarPicker dateTime = new CalendarPicker();
    dateTime.withCalendar(Calendar.getInstance());
    dateTime.withShowTime(Boolean.TRUE);
    dateTime.withLocale(Locale.ENGLISH);
    dateTime.calendarProperty().addListener(new ChangeListener<Calendar>() {

        public void changed(ObservableValue<? extends Calendar> ov, Calendar t, Calendar t1) {
            System.out.println("Selected date: "+t1.getTime().toString());
        }
    });
    StackPane root = new StackPane();
    root.getChildren().add(dateTime);

    Scene scene = new Scene(root, 300, 250);
    primaryStage.setTitle("Date & Time from JFXtras 2.2");
    primaryStage.setScene(scene);
    primaryStage.show();
}

然后在我的FXML中添加了一个按钮

<Button id="dateTimePicker" fx:id="dateTimePicker" layoutX="14.0" layoutY="398.0" mnemonicParsing="false" text="Start" />

最后初始化了我的Button

@FXML
private Button dateTimePicker,

我的按钮实际上没有做任何事情 - 没有新的窗户打开。我没有收到任何错误,但我确实在Eclipse中收到警告

Parameter 'primaryStage' is not assignable to javafx.event.Event

我做错了什么?

修改

向按钮添加onAction属性已停止我的应用程序正在运行。错误是:

 Error resolving onAction='#dateTimePicker', either the event handler is not in the Namespace or there is an error in the script.

1 个答案:

答案 0 :(得分:2)

假设您已为FXML文件设置了控制器,并且在该控制器中定义了dateTimePicker()方法。

首先,您需要使用按钮的onAction属性将按钮的操作映射到您定义的方法:

<Button id="dateTimePicker" fx:id="dateTimePicker" onAction="#dateTimePicker" layoutX="14.0" layoutY="398.0" mnemonicParsing="false" text="Start" />

处理程序方法需要采用与生成的事件类型匹配的参数(onActionActionEvent),或者不参数。这是您在Eclipse中收到警告的原因。由于您不需要访问事件本身,只需定义不带参数的方法:

@FXML
public void dateTimePicker(){

    // ...
}

最后,如果要显示新窗口,则必须创建一个新窗口。所以:

@FXML
public void dateTimePicker(){
    CalendarPicker dateTime = new CalendarPicker();
    dateTime.withCalendar(Calendar.getInstance());
    dateTime.withShowTime(Boolean.TRUE);
    dateTime.withLocale(Locale.ENGLISH);
    dateTime.calendarProperty().addListener(new ChangeListener<Calendar>() {

        public void changed(ObservableValue<? extends Calendar> ov, Calendar t, Calendar t1) {
            System.out.println("Selected date: "+t1.getTime().toString());
        }
    });
    StackPane root = new StackPane();
    root.getChildren().add(dateTime);

    Scene scene = new Scene(root, 300, 250);

    Stage stage = new Stage();

    stage.setTitle("Date & Time from JFXtras 2.2");
    stage.setScene(scene);
    stage.show();
}