1

I am a novice to javafx. I created a simple javafx fxml application. I defined a treeView in my fxml file. It is as follows,

FXMLDocument.fxml

 <AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml/1"      xmlns="http://javafx.com/javafx/2.2" fx:controller="scenebuilderfirst.FXMLDocumentController">
   <children>
     <TreeView id="" fx:id="tree" layoutX="60.0" layoutY="14.0" prefHeight="172.0" prefWidth="200.0" />
   </children>
 </AnchorPane>

and created the controller class as follows,

FXMLDocumentController.java

 public class FXMLDocumentController implements Initializable {

     @FXML
     private TreeView<?> tree;   

     @Override
     public void initialize(URL url, ResourceBundle rb) {

     }    
 }

my main java file is as follows,

MyApp.java

 public class SceneBuilderFirst extends Application {

     @Override
     public void start(Stage stage) throws Exception {
         AnchorPane root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

         Scene scene = new Scene(root);

         stage.setScene(scene);
         stage.show();

     }

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

Now I need to add tree items to the TreeView while running the program. So I thought of writing the following peace of code inside the initialize() method of my contorller class,

    // creating root item for the tree
    TreeItem<String> rootItem = new TreeItem<>("root");
    rootItem.setExpanded(true);
    //creating childern for the tree
    TreeItem<String>item1= new TreeItem<>("content1");
    rootItem.getChildren().add(item1);
    TreeItem<String>item2= new TreeItem<>("content2");
    rootItem.getChildren().add(item2);

    //attaching root item to tree
    tree = new TreeView<>(rootItem);

But it didn't work.

I need to set the TreeItems while running the program. Not through the fxml file. So I think I should do the coding in my main java file I need a way to access my TreeView after loading it via FXMLLoader in my main java file so i can make a TreeView on my own choice and attach it to this TreeView while running the program. Please guide me.

Shandigutt
  • 11
  • 3

1 Answers1

2

To fix this, replace

tree = new TreeView<>(rootItem);

with

tree.setRoot(rootItem);

For an explanation of why, see this discussion.

You also have to fix your declaration of the TreeView:

@FXML
private TreeView<String> tree;  
Community
  • 1
  • 1
James_D
  • 201,275
  • 16
  • 291
  • 322