JavaFX激活Datepicker下拉列表

时间:2015-04-21 03:08:26

标签: javafx datepicker fxml

当聚焦时,如何激活日期选择器的下拉日历?

Letter.FXML

<DatePicker fx:id="letterDatePicker" editable="false" focusTraversable="false" layoutX="184.0" layoutY="174.0" prefHeight="25.0" prefWidth="178.0" promptText="Select date">

FXMLControllerLetter.java

@FXML
private void companyName(ActionEvent event)
{
    if(fxTxtCompanyName.getText().isEmpty())
    {
        Stage letterStage = (Stage) ((Node) event.getSource()).getScene().getWindow();

        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle("Insufficient Data");
        alert.initOwner(letterStage);

        alert.setHeaderText("Lacking company name");
        alert.setContentText("Looks like you forgot to input the company name!");

        alert.showAndWait();
    }
    else
    {
        fxTxtCompanyName.setText(fxTxtCompanyName.getText().toUpperCase());
        letterDatePicker.requestFocus();
        letterDatePicker.show();
    }

}

日期格式转换器 - 我希望datepicker的格式为&#34; MMMM dd,yyyy&#34;所以我设置StringConverter以获得我想要的输出格式。

@Override
public void initialize(URL url, ResourceBundle rb) 
{
    // TODO
    fxLblCurrentDate.setText(dateNow());

    // <editor-fold defaultstate="collapsed" desc="DATE FORMAT CONVERTER">
    String pattern = "MMMM dd, yyyy";
    letterDatePicker.setConverter(new StringConverter<LocalDate>() 
    {
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(pattern);

        @Override
        public String toString(LocalDate date) 
        {
            if (date != null)
            {
                return dateFormatter.format(date);
            }
            else
            {
                return "";
            }
        }

        @Override
        public LocalDate fromString(String string) 
        {
            if (string != null && !string.isEmpty()) 
            {
                return LocalDate.parse(string, dateFormatter);
            }
            else
            {
                return null;
            }
        }
    });
    // </editor-fold>
}

1 个答案:

答案 0 :(得分:2)

调用它的show()方法。请参见下面的隐式完整示例:

@Override
public void start( Stage stage )
{

    final DatePicker datePicker = new DatePicker();
    datePicker.setEditable( false );
    datePicker.setFocusTraversable( false );
    datePicker.setPromptText( "Select date" );
    datePicker.setPrefWidth( 170 );

    Button b = new Button( "choose date" );
    b.setOnAction( new EventHandler<ActionEvent>()
    {
        @Override
        public void handle( ActionEvent event )
        {
            datePicker.show();
            datePicker.requestFocus();
        }
    } );

    Scene scene = new Scene( VBoxBuilder.create().children( datePicker, b ).build(), 800, 600 );
    stage.setScene( scene );
    stage.show();
}