FXML Variables not binding

一笑奈何 提交于 2019-12-01 14:47:23

You are trying to set the root item of the tree view in the controller's constructor.

When the FXMLLoader loads the fxml file, it will parse the fxml file, noting any fx:id attributes. It will instantiate the controller (by calling it's no-arg constructor), and then it will initialize any @FXML-annotated fields with the corresponding objects with matching fx:id attributes. When that is done, it calls the controller's initialize() method, if there is one.

So your constructor is executed before the noteTree is initialized by the FXMLLoader (and of course, this is the only order in which things could possibly happen). Hence when you call

    noteTree.setRoot(rootItem);

noteTree is still null.

The fix is simply to move the code in the constructor to the initialize method:

public class NoteKeeperController implements Initializable{
    NoteBook noteBook;
    TreeItem<String> rootItem;

    public BorderPane root;

    @FXML private TreeView<String> noteTree;

    @FXML private ScrollPane sp;
    @FXML private Button newNoteButton;

    @Override
    public void initialize(URL location, ResourceBundle resources){

        rootItem = new TreeItem<String> ("FirstNote");
        rootItem.setExpanded(true);     
        noteTree.setRoot(rootItem);

        noteBook= new NoteBook();

    }

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