0

I need to load JavaFX TreeView data at application startup. The problem is node lookup() method always return null.

CODE

public class Main extends Application {

    public static final String APPLICATION_NAME = "testapp" ;

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        String fxml = "/fxml/main-window.fxml";
        String globalCss = "/styles/main.css";
        FXMLLoader loader = new FXMLLoader(getClass().getResource(fxml));
        Parent root = (Parent) loader.load();
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.getScene().getStylesheets().add(globalCss);
        primaryStage.setMaximized(true);

        TreeView treevw = (TreeView) scene.lookup("#treevw");
        // lazy init here

        primaryStage.show();
    }
}

FXML

http://pastebin.com/aC2gHMjp

java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)

i've found this solution but it doesn't work for me (both).

Can anybody please help to solve the issue?

Community
  • 1
  • 1
tty
  • 314
  • 1
  • 2
  • 8

2 Answers2

4

lookup(...) will generally return null until a CSS pass has been made, which usually means you need to do it after showing the stage (but possibly after that).

But this is really not the right way to do what you're trying to do. Define a controller, set an fx:id on your TreeView and perform the initialization in the controller's initialize() method.

James_D
  • 201,275
  • 16
  • 291
  • 322
-1

In my experience, the JavaFX splitpane has a different structure than other subclasses of the Pane class. I have encountered this issue, how I fixed it was to call the getItems() to get an Item of the splitpane which should be a container type e.g. anchorpane, stackpane etc. then performed the lookup method there and it worked just fine.

FXMLLoader pageLoader = new FXMLLoader(LoginPageController.class.getResource("FriendListPage.fxml"));
        SplitPane friendListPage = (SplitPane) pageLoader.load();    

AnchorPane addFriendSubWindow = (AnchorPane) friendListPage.getItems().get(0);

        Button btnCloseFriendWindow = (Button) addFriendSubWindow.lookup("#btnCloseFriendWindow");
        
        btnCloseFriendWindow.setOnAction(event -> {
            if(!extraPanelContainer.getChildren().isEmpty())
                extraPanelContainer.getChildren().clear();
            clearFriendList(friendListPage);
        });

the btnCloseFriendWindow.setOnAction() used to return null, till I used this approach.