无法填充我的JavaFX ComboBox

时间:2017-07-18 09:12:57

标签: java javafx combobox

我无法填充从Scene Builder创建的JavaFX ComboBox。虽然我已经搜索过,但我无法找到解决此错误的方法。

以下示例均无效。

@FXML ComboBox ComboStatus;

@Override
    public void initialize(URL url, ResourceBundle rbs) {           
        ComboStatus.getItems().addAll("Single","Married");
    }
ObservableList<String> statusList = FXCollections.
            observableArrayList(
                    "Single",
                    "Married"
    );

@FXML ComboBox<String> ComboStatus;

@Override
    public void initialize(URL url, ResourceBundle rbs) {
        // TODO Auto-generated method stub
        ComboStatus.setItems(statusList);
    }

帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

以下是一个有效的代码示例,希望有所帮助:

扩展应用程序的类:

public class Test extends Application{

    public static void main(String[] args) {
        Application.launch(Test.class, args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        FXMLLoader loader = new 
           FXMLLoader(Test.class.getResource("/test/MyExample.fxml"));
        AnchorPane pane = (AnchorPane)loader.load();
        Scene scene = new Scene(pane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

控制器类:

public class MyExampleController implements Initializable {

    //I think the problem with your code was that you did not use 
    //ComboBox<String>
    @FXML
    private ComboBox<String> cbxStatus;


    @Override
    public void initialize(URL url, ResourceBundle rb) {
        cbxStatus.getItems().addAll("Single", "Married");
        //you can make it so that an item is already selected
        //instead of no item being selected until the user clicks on the box 
        //to select
        cbxStatus.getSelectionModel().select(0);
    }    

}
相关问题