Example usage for javafx.scene.control TreeItem getChildren

List of usage examples for javafx.scene.control TreeItem getChildren

Introduction

In this page you can find the example usage for javafx.scene.control TreeItem getChildren.

Prototype

public ObservableList<TreeItem<T>> getChildren() 

Source Link

Document

The children of this TreeItem.

Usage

From source file:ubicrypt.ui.files.FilesController.java

private synchronized TreeItem<ITreeItem> addFiles(final Iterator<Path> it, final Path rootPath,
        final TreeItem<ITreeItem> root, final LocalFile file) {
    if (!it.hasNext()) {
        return root;
    }/* w  w w  .j a va  2 s. c o  m*/
    final Path path = it.next();
    final Path resolvedPath = rootPath.resolve(path);
    if (Files.isRegularFile(resolvedPath)) {
        final FileItem item = new FileItem(file);
        final TreeItem<ITreeItem> fileItem = new TreeItem<>(item);
        root.getChildren().add(fileItem);
        root.getChildren().sort((iTreeItemTreeItem, t1) -> iTreeItemTreeItem.getValue().getLabel()
                .compareTo(t1.getValue().getLabel()));
        return fileItem;
    }
    final Optional<TreeItem<ITreeItem>> optTreeItem = root.getChildren().stream()
            .filter(ti -> ((FolderItem) ti.getValue()).getPath().equals(path)).findFirst();
    if (optTreeItem.isPresent()) {
        return addFiles(it, resolvedPath, optTreeItem.get(), file);
    }
    final TreeItem<ITreeItem> fileItem = new TreeFolderItem(new FolderItem(path,
            event -> fileAdder.accept(resolvedPath), event -> folderAdder.accept(resolvedPath)));
    root.getChildren().add(fileItem);
    root.getChildren().sort((iTreeItemTreeItem, t1) -> iTreeItemTreeItem.getValue().getLabel()
            .compareTo(t1.getValue().getLabel()));
    return addFiles(it, resolvedPath, fileItem, file);
}

From source file:com.heliosdecompiler.helios.gui.controller.FileTreeController.java

@FXML
public void initialize() {
    this.rootItem = new TreeItem<>(new TreeNode("[root]"));
    this.root.setRoot(this.rootItem);
    this.root.setCellFactory(new TreeCellFactory<>(node -> {
        if (node.getParent() == null) {
            ContextMenu export = new ContextMenu();

            MenuItem exportItem = new MenuItem("Export");

            export.setOnAction(e -> {
                File file = messageHandler.chooseFile().withInitialDirectory(new File("."))
                        .withTitle(Message.GENERIC_CHOOSE_EXPORT_LOCATION_JAR.format())
                        .withExtensionFilter(new FileFilter(Message.FILETYPE_JAVA_ARCHIVE.format(), "*.jar"),
                                true)//from ww w  . j a  v  a2 s. c  om
                        .promptSave();

                OpenedFile openedFile = (OpenedFile) node.getMetadata().get(OpenedFile.OPENED_FILE);

                Map<String, byte[]> clone = new HashMap<>(openedFile.getContents());

                backgroundTaskHelper.submit(
                        new BackgroundTask(Message.TASK_SAVING_FILE.format(node.getDisplayName()), true, () -> {
                            try {
                                if (!file.exists()) {
                                    if (!file.createNewFile()) {
                                        throw new IOException("Could not create export file");
                                    }
                                }

                                try (ZipOutputStream zipOutputStream = new ZipOutputStream(
                                        new FileOutputStream(file))) {
                                    for (Map.Entry<String, byte[]> ent : clone.entrySet()) {
                                        ZipEntry zipEntry = new ZipEntry(ent.getKey());
                                        zipOutputStream.putNextEntry(zipEntry);
                                        zipOutputStream.write(ent.getValue());
                                        zipOutputStream.closeEntry();
                                    }
                                }

                                messageHandler.handleMessage(Message.GENERIC_EXPORTED.format());
                            } catch (IOException ex) {
                                messageHandler.handleException(Message.ERROR_IOEXCEPTION_OCCURRED.format(), ex);
                            }
                        }));
            });

            export.getItems().add(exportItem);
            return export;
        }
        return null;
    }));

    root.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
        if (event.getCode() == KeyCode.ENTER) {
            TreeItem<TreeNode> selected = this.root.getSelectionModel().getSelectedItem();
            if (selected != null) {
                if (selected.getChildren().size() != 0) {
                    selected.setExpanded(!selected.isExpanded());
                } else {
                    getParentController().getAllFilesViewerController().handleClick(selected.getValue());
                }
            }
        }
    });

    Tooltip tooltip = new Tooltip();
    StringBuilder search = new StringBuilder();

    List<TreeItem<TreeNode>> searchContext = new ArrayList<>();
    AtomicInteger searchIndex = new AtomicInteger();

    root.focusedProperty().addListener((observable, oldValue, newValue) -> {
        if (!newValue) {
            tooltip.hide();
            search.setLength(0);
        }
    });

    root.boundsInLocalProperty().addListener((observable, oldValue, newValue) -> {
        Bounds bounds = root.localToScreen(newValue);
        tooltip.setAnchorX(bounds.getMinX());
        tooltip.setAnchorY(bounds.getMinY());
    });

    root.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
        if (tooltip.isShowing() && event.getCode() == KeyCode.UP) {
            if (searchIndex.decrementAndGet() < 0) {
                searchIndex.set(searchContext.size() - 1);
            }
        } else if (tooltip.isShowing() && event.getCode() == KeyCode.DOWN) {
            if (searchIndex.incrementAndGet() >= searchContext.size()) {
                searchIndex.set(0);
            }
        } else {
            return;
        }
        event.consume();

        root.scrollTo(root.getRow(searchContext.get(searchIndex.get())));
        root.getSelectionModel().select(searchContext.get(searchIndex.get()));
    });

    root.addEventHandler(KeyEvent.KEY_TYPED, event -> {
        if (event.getCharacter().charAt(0) == '\b') {
            if (search.length() > 0) {
                search.setLength(search.length() - 1);
            }
        } else if (event.getCharacter().charAt(0) == '\u001B') { //esc
            tooltip.hide();
            search.setLength(0);
            return;
        } else if (search.length() > 0
                || (search.length() == 0 && StringUtils.isAlphanumeric(event.getCharacter()))) {
            search.append(event.getCharacter());
            if (!tooltip.isShowing()) {
                tooltip.show(root.getScene().getWindow());
            }
        }

        if (!tooltip.isShowing())
            return;

        String str = search.toString();
        tooltip.setText("Search for: " + str);

        searchContext.clear();

        ArrayDeque<TreeItem<TreeNode>> deque = new ArrayDeque<>();
        deque.addAll(rootItem.getChildren());

        while (!deque.isEmpty()) {
            TreeItem<TreeNode> item = deque.poll();
            if (item.getValue().getDisplayName().contains(str)) {
                searchContext.add(item);
            }
            if (item.isExpanded() && item.getChildren().size() > 0)
                deque.addAll(item.getChildren());
        }

        searchIndex.set(0);
        if (searchContext.size() > 0) {
            root.scrollTo(root.getRow(searchContext.get(0)));
            root.getSelectionModel().select(searchContext.get(0));
        }
    });

    openedFileController.loadedFiles().addListener((MapChangeListener<String, OpenedFile>) change -> {
        if (change.getValueAdded() != null) {
            updateTree(change.getValueAdded());
        }
        if (change.getValueRemoved() != null) {
            this.rootItem.getChildren()
                    .removeIf(ti -> ti.getValue().equals(change.getValueRemoved().getRoot()));
        }
    });
}

From source file:caillou.company.clonemanager.gui.customComponent.excludeTree.ExcludeTreeController.java

public void buildTreeLazily(final TreeItem<DirectoryLazyCheckableTreeItem> currentItem, int nbPass) {
    if (nbPass == 0) {
        return;/* w  w w  .ja  v  a2  s  . c  om*/
    }

    boolean lazyChilds = nbPass > 2;
    DirectoryLazyCheckableTreeItem currentItemValue = currentItem.getValue();
    final ExcludeTreeController excludeControllerInstance = this;

    File currentDirectory = new File(currentItemValue.getAbsolutePath());
    if (!currentDirectory.canRead()) {
        return;
    }

    currentItemValue.setLoaded(lazyChilds);
    currentItem.getChildren().clear();

    for (File subFile : currentDirectory.listFiles(directoryFilter)) {
        TreeItem<DirectoryLazyCheckableTreeItem> children = new CheckBoxTreeItem<>(
                this.factoryDirectoryCheckableTreeItem.createItem(subFile.getAbsolutePath()));
        this.buildTreeLazily(children, nbPass - 1);
        currentItem.getChildren().add(children);
    }

    if (nbPass == 2) {
        currentItem.expandedProperty().addListener(new ChangeListener<Boolean>() {
            @Override
            public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue,
                    Boolean newValue) {
                excludeControllerInstance.buildTreeLazily(currentItem, 3);
                currentItem.expandedProperty().removeListener(this);
            }
        });
    }

}

From source file:eu.fthevenet.binjr.sources.jrds.adapters.JrdsDataAdapter.java

private void attachNode(TreeItem<TimeSeriesBinding<Double>> tree, String id, Map<String, JsonJrdsItem> nodes)
        throws DataAdapterException {
    JsonJrdsItem n = nodes.get(id);/*from w  w  w . j  a va  2 s. c om*/
    String currentPath = normalizeId(n.id);
    TreeItem<TimeSeriesBinding<Double>> newBranch = new TreeItem<>(
            bindingFactory.of(tree.getValue().getTreeHierarchy(), n.name, currentPath, this));

    if (JRDS_FILTER.equals(n.type)) {
        // add a dummy node so that the branch can be expanded
        newBranch.getChildren().add(new TreeItem<>(null));
        // add a listener that will get the treeview filtered according to the selected filter/tag
        newBranch.expandedProperty().addListener(new FilteredViewListener(n, newBranch));
    } else {
        if (n.children != null) {
            for (JsonJrdsItem.JsonTreeRef ref : n.children) {
                attachNode(newBranch, ref._reference, nodes);
            }
        } else {
            // add a dummy node so that the branch can be expanded
            newBranch.getChildren().add(new TreeItem<>(null));
            // add a listener so that bindings for individual datastore are added lazily to avoid
            // dozens of individual call to "graphdesc" when the tree is built.
            newBranch.expandedProperty().addListener(new GraphDescListener(currentPath, newBranch, tree));
        }
    }
    tree.getChildren().add(newBranch);
}

From source file:net.rptools.tokentool.client.TokenTool.java

/**
 * // www  .  j a  v a 2  s.co m
 * @author Jamz
 * @throws IOException
 * @since 2.0
 * 
 *        This method loads and processes all the overlays found in user.home/overlays and it can take a minute to load as it creates thumbnail versions for the comboBox so we call this during the
 *        init and display progress in the preLoader (splash screen).
 * 
 */
private TreeItem<Path> cacheOverlays(File dir, TreeItem<Path> parent, int THUMB_SIZE) throws IOException {
    TreeItem<Path> root = new TreeItem<>(dir.toPath());
    root.setExpanded(false);

    log.debug("caching " + dir.getAbsolutePath());

    File[] files = dir.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            cacheOverlays(file, root, THUMB_SIZE);
        } else {
            Path filePath = file.toPath();
            TreeItem<Path> imageNode = new TreeItem<>(filePath,
                    ImageUtil.getOverlayThumb(new ImageView(), filePath));
            root.getChildren().add(imageNode);

            notifyPreloader(new Preloader.ProgressNotification((double) loadCount++ / overlayCount));
        }
    }

    if (parent != null) {
        // When we show the overlay image, the TreeItem value is "" so we need to
        // sort those to the bottom for a cleaner look and keep sub dir's at the top.
        // If a node has no children then it's an overlay, otherwise it's a directory...
        root.getChildren().sort(new Comparator<TreeItem<Path>>() {
            @Override
            public int compare(TreeItem<Path> o1, TreeItem<Path> o2) {
                if (o1.getChildren().size() == 0 && o2.getChildren().size() == 0)
                    return 0;
                else if (o1.getChildren().size() == 0)
                    return Integer.MAX_VALUE;
                else if (o2.getChildren().size() == 0)
                    return Integer.MIN_VALUE;
                else
                    return o1.getValue().compareTo(o2.getValue());
            }
        });

        parent.getChildren().add(root);
    }

    return root;
}

From source file:org.jevis.jeconfig.plugin.classes.ClassTree.java

private void getAllExpanded(List<TreeItem<JEVisClass>> list, TreeItem<JEVisClass> item) {
    if (item.isExpanded()) {
        list.add(item);/* w w w. j a va 2 s  .c  om*/
        for (TreeItem<JEVisClass> i : item.getChildren()) {
            getAllExpanded(list, i);
        }
    }
}

From source file:ubicrypt.ui.ctrl.HomeController.java

private synchronized TreeItem<ITreeItem> addFiles(final Iterator<Path> it, final Path rootPath,
        final TreeItem<ITreeItem> root, final LocalFile file) {
    if (!it.hasNext()) {
        return root;
    }//from  www.ja v  a2  s  .com
    final Path path = it.next();
    final Path resolvedPath = rootPath.resolve(path);
    if (Files.isRegularFile(resolvedPath)) {
        final FileItem item = applicationContext.getBean(FileItem.class, file);
        final TreeItem<ITreeItem> fileItem = new TreeItem<>(item);
        root.getChildren().add(fileItem);
        return fileItem;
    }
    final Optional<TreeItem<ITreeItem>> optTreeItem = root.getChildren().stream()
            .filter(ti -> ((FolderItem) ti.getValue()).getPath().equals(path)).findFirst();
    if (optTreeItem.isPresent()) {
        return addFiles(it, resolvedPath, optTreeItem.get(), file);
    }
    final TreeItem<ITreeItem> fileItem = new TreeFolderItem(
            new FolderItem(path, event -> fileAdder.accept(resolvedPath)));
    root.getChildren().add(fileItem);
    return addFiles(it, resolvedPath, fileItem, file);
}

From source file:org.jevis.jeconfig.plugin.classes.ClassTree.java

private void expandAll(List<TreeItem<JEVisClass>> list, TreeItem<JEVisClass> root) {
    //        System.out.println("expand all");
    for (final TreeItem<JEVisClass> item : root.getChildren()) {
        for (final TreeItem<JEVisClass> child : list) {
            try {
                if (item.getValue().getName().equals(child.getValue().getName())) {
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            item.setExpanded(true);
                        }//from w  w w  .ja  v a 2 s  . c om
                    });

                }
            } catch (JEVisException ex) {
                ex.printStackTrace();
            }
        }
        expandAll(list, item);
    }
}

From source file:org.beryx.viewreka.fxapp.BundleChooser.java

@SuppressWarnings("deprecation")
@Override//from   w  w  w.  j  av  a2  s.  c o  m
public void initialize(URL location, ResourceBundle resources) {
    check("ttvBundles", ttvBundles);
    check("ttColName", ttColName);
    check("ttColVersion", ttColVersion);
    check("ttColId", ttColId);
    check("ttColDescription", ttColDescription);

    ttvBundles.getColumns().forEach(col -> col.impl_setReorderable(false));

    CatalogManager catalogManager = new CatalogManager(guiSettingsManager.getSettings());
    Map<String, Map<Pair<String, Version>, BundleInfo>> categoryMap = new TreeMap<>();
    catalogManager.getCatalogUrls().forEach(url -> {
        CatalogRepo repo = new CatalogRepo(url, catalogManager.getCatalogCache());
        List<BundleInfo> infoEntries = Collections.emptyList();
        try {
            infoEntries = repo.getEntries();
        } catch (Exception e) {
            Dialogs.error("Cannot read from repository " + repo.getCatalogUrl(), e.getMessage(), e);
        }
        infoEntries.forEach(entry -> entry.getCategories().forEach(category -> {
            Map<Pair<String, Version>, BundleInfo> idMap = categoryMap.get(category);
            if (idMap == null) {
                idMap = new TreeMap<>();
                categoryMap.put(category, idMap);
            }
            String bundleId = entry.getId();
            Version version = entry.getVersion();
            Pair<String, Version> infoPair = new ImmutablePair<>(bundleId, version);
            BundleInfo oldEntry = idMap.get(infoPair);
            if (oldEntry == null) {
                idMap.put(infoPair, entry);
            } else if (entry.getUrl().equals(oldEntry.getUrl())) {
                log.warn("Different URLs for " + entry.getName() + " " + version + ": " + entry.getUrl()
                        + " and " + oldEntry.getUrl());
            }
        }));
    });

    ttvBundles.setRowFactory(item -> new BundleInfoTreeTableRow());
    ttColName.setCellFactory(p -> new BundleInfoNameTreeTableCell<>());

    ttColName.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getValue()));
    ttColVersion.setCellValueFactory(
            param -> new ReadOnlyStringWrapper(param.getValue().getValue().getVersion().toString()));
    ttColId.setCellValueFactory(param -> new ReadOnlyStringWrapper(param.getValue().getValue().getId()));
    ttColDescription.setCellValueFactory(
            param -> new ReadOnlyStringWrapper(param.getValue().getValue().getDescription()));

    TreeItem<BundleInfo> root = new TreeItem<>(new NullBundleInfo("Bundles"));
    root.setExpanded(true);
    ttvBundles.setRoot(root);
    ttvBundles.setShowRoot(false);
    categoryMap.entrySet().forEach(categoryEntry -> {
        String category = categoryEntry.getKey();
        TreeItem<BundleInfo> categoryItem = new TreeItem<>(new NullBundleInfo(category));
        categoryItem.setExpanded(true);
        root.getChildren().add(categoryItem);

        List<BundleInfo> bInfo = new ArrayList<>(categoryEntry.getValue().values());
        bInfo.sort((b1, b2) -> {
            int res = b1.getName().compareTo(b2.getName());
            if (res == 0) {
                res = b1.getVersion().compareTo(b2.getVersion());
            }
            return res;
        });
        bInfo.forEach(bundleInfo -> {
            boolean existing = existingBundles.stream()
                    .anyMatch(pair -> bundleInfo.getId().equals(pair.getKey())
                            && bundleInfo.getVersion().equals(pair.getValue()));
            BundleInfoTreeItem bundleItem = new BundleInfoTreeItem(bundleInfo, existing);

            bundleItem.setIndependent(true);
            Pair<String, Version> infoPair = new ImmutablePair<>(bundleInfo.getId(), bundleInfo.getVersion());
            bundleItem.setSelected(initialInfoEntries.stream().anyMatch(
                    entry -> new ImmutablePair<>(entry.getId(), entry.getVersion()).equals(infoPair)));
            bundleItem.selectedProperty()
                    .addListener((obs, oldVal, newVal) -> updateSelection(bundleInfo, newVal));
            categoryItem.getChildren().add(bundleItem);
        });
    });
}

From source file:org.jevis.jeconfig.plugin.classes.ClassTree.java

private void expand(TreeItem<JEVisClass> item, boolean expand) {
    if (!item.isLeaf()) {
        if (item.isExpanded() && !expand) {
            item.setExpanded(expand);/*from w  ww.java2s . co  m*/
        } else if (!item.isExpanded() && expand) {
            item.setExpanded(expand);
        }

        for (TreeItem<JEVisClass> child : item.getChildren()) {
            expand(child, expand);
        }
    }
}