JavaFX更改ComboBox项(在initialize()方法之外)

时间:2018-01-04 14:59:02

标签: javafx combobox fxml

我正在玩SceneBuilder并遇到一些关于intialize()方法的问题以及如何在已经在所述方法中初始化之后更改ComboBox项。所以基本上,在我设置初始化项目后,我无法再从控制器中的另一个方法更改它们。

这是我的代码:

public class AppController implements Initializable {

    private ObservableList<String> list = FXCollections.observableArrayList();
    private MainModel model;

    @FXML
    private ComboBox<String> cobUsers = new ComboBox<String>();

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        list.add("name1");
        list.add("name2");

        cobUsers.setItems(list); // this works!
    }   

    public void initModel(MainModel model) {
        this.model = model;
    }

    public void addItems(){
        list.add("name3");
        list.add("name4");

        cobUsers.setItems(list); // this does not work. ComboBox items remain "name1" and "name2"
    }
}


public class App extends Application {

    private Stage primaryStage;
    private AnchorPane rootLayout;
    private AppController appController = new AppController();
    MainModel model = new MainModel();

    @Override
    public void start(Stage primaryStage) {
        appController.initModel(model);

        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("App");

        initRootLayout();

        appController.addItems();
    }

    /**
     * Initializes the root layout.
     */
    public void initRootLayout() {
        try {
            // Load root layout from fxml file.
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(getClass().getResource("FXMLDocument.fxml"));
            rootLayout = (AnchorPane) loader.load();

            // Show the scene containing the root layout.
            Scene scene = new Scene(rootLayout);
            primaryStage.setScene(scene);
            primaryStage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }
}

我想我的问题是,如何在ComboBox初始化intialize()之后如何访问/更改我的initRootLayout()

谢谢! :)

更新1:

我更改了App课程中的list(见下文),现在就可以了。 ComboBox现在包含4个项目,所有这些项目在调用addItems()后显示在public void initRootLayout() { try { // Load root layout from fxml file. FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("FXMLDocument.fxml")); rootLayout = (AnchorPane) loader.load(); AppController controller = loader.<AppController>getController(); controller.addItems(); // Show the scene containing the root layout. Scene scene = new Scene(rootLayout); primaryStage.setScene(scene); primaryStage.show(); } catch (IOException e) { e.printStackTrace(); } } 中。谢谢大家!

{{ route('route_name') }}

0 个答案:

没有答案