JavaFX 2.0 + FXML - strange lookup behaviour

前端 未结 2 1999
南方客
南方客 2020-12-11 06:21

I want to find a VBox node in a scene loaded with FXMLoader thanks to Node#lookup() but I get the following exception :

java.lang.Cla

相关标签:
2条回答
  • 2020-12-11 06:44

    The easiest way to get a reference to the VBox is by calling FXMLLoader#getNamespace(). For example:

    VBox myvbox = (VBox)fxmlLoader.getNamespace().get("myvbox");
    

    Note that you'll need to create an instance of FXMLLoader and call the non-static version of load() in order for this to work:

    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("test.fxml"));
    AnchorPane page = (AnchorPane) fxmlLoader.load();
    
    0 讨论(0)
  • 2020-12-11 06:46
    1. SplitPane puts all items in separate stack panes (fancied as SplitPaneSkin$Content). For unknown reason FXMLLoader assign them the same id as root child. You can get VBox you need by next utility method:

      public <T> T lookup(Node parent, String id, Class<T> clazz) {
          for (Node node : parent.lookupAll(id)) {
              if (node.getClass().isAssignableFrom(clazz)) {
                  return (T)node;
              }
          }
          throw new IllegalArgumentException("Parent " + parent + " doesn't contain node with id " + id);
      }
      

      and use it next way:

      VBox myvbox = lookup(page, "#myvbox", VBox.class);
      myvbox.getChildren().add(new Button("Hello world !!!"));
      
    2. you can use Controller and add autopopulated field:

      @FXML
      VBox myvbox;
      
    0 讨论(0)
提交回复
热议问题