Java方法调用匿名类

时间:2016-01-19 17:39:32

标签: java class methods treeview

我对此代码有疑问(从java2s.com中复制):

  private TreeItem<File> createNode(final File f) {
    return new TreeItem<File>(f) {
      private boolean isLeaf;
      private boolean isFirstTimeChildren = true;
      private boolean isFirstTimeLeaf = true;

      @Override
      public ObservableList<TreeItem<File>> getChildren() {
        super.getChildren().setAll(buildChildren(this));
        return super.getChildren();
      }

      @Override
      public boolean isLeaf() {
        return isLeaf;
      }

      private ObservableList<TreeItem<File>> buildChildren(
          TreeItem<File> TreeItem) {
        File f = TreeItem.getValue();
        if (f == null) {
          return FXCollections.emptyObservableList();
        }
        if (f.isFile()) {
          return FXCollections.emptyObservableList();
        }
        File[] files = f.listFiles();
        if (files != null) {
          ObservableList<TreeItem<File>> children = FXCollections
              .observableArrayList();
          for (File childFile : files) {
            children.add(createNode(childFile));
          }
          return children;
        }
        return FXCollections.emptyObservableList();
      }
    };
  }

  @Override
  public void start(Stage stage) {
    Scene scene = new Scene(new Group(), 300, 300);
    VBox vbox = new VBox();

    TreeItem<File> root = createNode(new File("c:/"));
    TreeView treeView = new TreeView<File>(root);

    vbox.getChildren().add(treeView);
    ((Group) scene.getRoot()).getChildren().add(vbox);

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

我真的不明白为什么,例如,&#34; buildChildren&#34;方法被调用。 因为没有调用TreeItem-anonymousclass的方法 &#34;开始&#34;功能。只需调用方法&#34; createNode&#34;初始化TreeItem。

祝你好运 史蒂夫

1 个答案:

答案 0 :(得分:0)

在您提供的代码中,buildChildren(..)仅从getChildren()调用。由于这个方法覆盖了超类的方法,我们可以参考超类的JavaDoc

  

public ObservableList<TreeItem<T>> getChildren()

     

这个TreeItem的孩子们。经常调用此方法,因此建议由任何TreeItem实现缓存返回的列表。

     

<强>返回:   包含属于TreeItem的子TreeItem的列表。

这给出了一个事实,即该方法由代码使用的JavaFX库调用。

如果您想知道何时调用此方法,可以使用调试器在getChildren()方法中设置断点。在Eclipse中运行此代码时,我发现在单击以展开GUI中的根getChildren()时首先调用TreeItem。调试器视图显示buildChildren()确实调用了getChildren(),而TreeItem中的其他代码又调用了Dim oContextMenu As CommandBar Dim oContextMenuItem As CommandBarControl 'Make changes to the ActiceDocument only (this is needed to make any changes to this document). CustomizationContext = ActiveDocument For Each oContextMenu In ActiveDocument.CommandBars If oContextMenu.Type = MsoBarType.msoBarTypePopup Then 'Loop through all the context menus of type (msoBarTypePopup) For Each oContextMenuItem In oContextMenu.Controls If (InStr(oContextMenuItem.Caption, "Smokeball")) Then oContextMenuItem.Delete End If Next End If Next

call stack for getChildren

相关问题