Cannot invoke “javafx.scene.control.ComboBox.getItems()” because the return value of “Controller.getMyBox()” is null

五迷三道 提交于 2020-12-27 05:36:34

问题


Somehow, I cannot add items to my ComboBox variable from another class as it always says either the value of variable is null or the return value of its getter is null.

I use Scene Builder to build Sample.fxml, with controller as Controller class, luanch the whole thing form UserInterface class

FXML

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.layout.BorderPane?>

<BorderPane xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="Controller">
   <center>
      <ComboBox fx:id="myBox" prefWidth="150.0" BorderPane.alignment="CENTER" />
   </center>
</BorderPane>

Controller

public class Controller {
    @FXML
    private ComboBox<String> myBox;

    public ComboBox<String> getMyBox() {
        return myBox;
    }

    public void initialize() {
        ObservableList<String> defaultTicker = FXCollections.observableArrayList("Something");
        myBox.getItems().addAll(defaultTicker);
    }
}

UserInterface

public class UserInterface extends Application {
    @Override
    public void start(Stage primaryStage) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("Sample.fxml"));
            Parent root = loader.load();
            Controller controller = new Controller();

            primaryStage.setTitle("Title");
            primaryStage.setScene(new Scene(root));
            primaryStage.show();

            List<String> addStuff = new ArrayList<String>();
            addStuff.add("a");
            addStuff.add("b");
            addStuff.add("c");
            controller.getMyBox().getItems().addAll(addStuff);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}

After running, the interface appears, with only the option "Something" in it. So I guess it initialize fine? The interface after launch

What did I do wrong? I couldn't seem to find any solutions so far.

Thanks in advance.

来源:https://stackoverflow.com/questions/65391471/cannot-invoke-javafx-scene-control-combobox-getitems-because-the-return-valu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!