Search code examples
javajavafxscenebuilder

javafx choicebox to trigger a method onchange


I am very rusty on my java and even more on javafx. so I got a choicebox "categoryDrop" that when the value of the choicebox change I want to trigger this event that then takes the value of the choicebox and compare to an object "Folder" categorylist which is an attribute it has.

here is my code

  @FXML 
private void folderByCategory(ActionEvent event) {
    System.out.println("här1");
      TreeItem<DocumentObject<?>> treeRoot = new TreeItem<>(new Folder());
    
    for (Folder folder : logic.getFolderList()) {
        
        if(f.getCategoryList().contains(categoryDrop.valueProperty())){
            System.out.println("här2");
          TreeItem<DocumentObject<?>> newFolders = new TreeItem<>(folder);
          
          for(FileReference file : folder.getFileList()){
            System.out.println(file.getName());
            TreeItem<DocumentObject<?>> fileNode = new TreeItem<>(file);
            newFolders.getChildren().add(fileNode);
        }
          
         treeRoot.getChildren().add(newFolders);
          treeRoot.setExpanded(true);
       }
        treeNav.setRoot(treeRoot);
    }
}

But then when I looked in scenebuilder I didn't see any good way to implement the method so it triggers when it changes. Anyone know a better way to do this? Should I use a listener instead maybe?


Solution

  • ChoiceBox has an onAction property, so in FXML you can simply assign this controller method to this property:

    <ChoiceBox fx:id="categoryDrop" onAction="#folderByCategory" />
    

    Unfortunately, the current version of Scene Builder does not support this property, so you cannot set this directly from Scene Builder. There is a current issue filed for this.

    Some workarounds are:

    1. Edit the FXML manually to add the onAction attribute, as above.
    2. Use a ComboBox instead of a ChoiceBox. The functionality is similar (though not identical) and a ComboBox will likely do what you need. Scene Builder does support the onAction property of a ComboBox.
    3. Register the handler in the controller's initialize() method instead. All you need is

      @FXML
      private ChoiceBox<...> categoryDrop ;
      
      public void initialize() {
          categoryDrop.setOnAction(this::folderByCategory);
          // existing code ...
      }
      
      @FXML
      private void folderByCategory(ActionEvent event) {
          // existing code...
      }