Example usage for javafx.scene.control TreeItem setExpanded

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

Introduction

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

Prototype

public final void setExpanded(boolean value) 

Source Link

Document

Sets the expanded state of this TreeItem.

Usage

From source file:sonicScream.controllers.CategoryTabController.java

private void recursiveSetNodeExpanded(TreeItem<String> root, boolean expanded) {
    if (root.getParent() != null) //Don't want to collapse the root!
    {//from  w  w  w  . ja va  2 s. c  om
        root.setExpanded(expanded);
    }
    for (TreeItem<String> item : root.getChildren()) {
        if (item.getChildren().isEmpty()) {
            item.setExpanded(expanded);
        } else {
            recursiveSetNodeExpanded(item, expanded);
        }
    }
}

From source file:org.sleuthkit.autopsy.imageanalyzer.gui.navpanel.NavPanel.java

/**
 * Set the tree to the passed in group//w  w  w. j a va  2  s.  c  om
 *
 * @param grouping
 */
public void setFocusedGroup(DrawableGroup grouping) {

    List<String> path = groupingToPath(grouping);

    final GroupTreeItem treeItemForGroup = ((GroupTreeItem) activeTreeProperty.get().getRoot())
            .getTreeItemForPath(path);

    if (treeItemForGroup != null) {
        Platform.runLater(() -> {
            TreeItem<TreeNode> ti = treeItemForGroup;
            while (ti != null) {
                ti.setExpanded(true);
                ti = ti.getParent();
            }
            int row = activeTreeProperty.get().getRow(treeItemForGroup);
            if (row != -1) {
                activeTreeProperty.get().getSelectionModel().select(treeItemForGroup);
                activeTreeProperty.get().scrollTo(row);
            }
        });
    }
}

From source file:Testing.TestMain.java

private void fileFinder(File dir, TreeItem<File> parent) throws IOException {
    String[] extensions = new String[] { "mp3" };
    TreeItem<File> root = new TreeItem<>(dir);
    root.setExpanded(true);
    dir.getCanonicalPath();//from ww w . j  av  a  2s . c o m

    List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
    //Collection collector = hyperStackOverflowFileMp3Scan(dir);
    //File[] files = null;
    //collector.toArray(files);

    for (File file : files) {
        if (!file.toString().contains("$RECYCLE.BIN")) {
            if (file.isDirectory()) {
                System.out.println("directory:" + file.getCanonicalPath());
                fileFinder(file, root);
            } else {
                System.out.println("    file:" + file.getCanonicalPath());
                root.getChildren().add(new TreeItem<>(file));
            }
        }
    }
    if (parent == null) {
        //treeViewFile.setRoot(root);
    } else {
        parent.getChildren().add(root);
    }
}

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

@SuppressWarnings("deprecation")
@Override//  ww w.jav a2 s.  com
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:edu.mit.lib.handbag.Controller.java

public void initialize() {

    Image wfIm = new Image(getClass().getResourceAsStream("/SiteMap.png"));
    workflowLabel.setGraphic(new ImageView(wfIm));
    workflowLabel.setContentDisplay(ContentDisplay.BOTTOM);

    workflowChoiceBox.addEventHandler(ActionEvent.ACTION, event -> {
        if (workflowChoiceBox.getItems().size() != 0) {
            return;
        }//from   w w w.j av  a  2  s  .  c om
        ObservableList<Workflow> wflowList = FXCollections.observableArrayList(loadWorkflows());
        workflowChoiceBox.setItems(wflowList);
        workflowChoiceBox.getSelectionModel().selectedIndexProperty().addListener((ov, value, new_value) -> {
            int newVal = (int) new_value;
            if (newVal != -1) {
                Workflow newSel = workflowChoiceBox.getItems().get(newVal);
                if (newSel != null) {
                    workflowLabel.setText(newSel.getName());
                    generateBagName(newSel.getBagNameGenerator());
                    bagLabel.setText(bagName);
                    sendButton.setText(newSel.getDestinationName());
                    setMetadataList(newSel);
                }
            }
        });
    });

    Image bagIm = new Image(getClass().getResourceAsStream("/Bag.png"));
    bagLabel.setGraphic(new ImageView(bagIm));
    bagLabel.setContentDisplay(ContentDisplay.BOTTOM);

    Image sendIm = new Image(getClass().getResourceAsStream("/Cabinet.png"));
    sendButton.setGraphic(new ImageView(sendIm));
    sendButton.setContentDisplay(ContentDisplay.BOTTOM);
    sendButton.setDisable(true);
    sendButton.setOnAction(e -> transmitBag());

    Image trashIm = new Image(getClass().getResourceAsStream("/Bin.png"));
    trashButton.setGraphic(new ImageView(trashIm));
    trashButton.setContentDisplay(ContentDisplay.BOTTOM);
    trashButton.setDisable(true);
    trashButton.setOnAction(e -> reset(false));

    TreeItem<PathRef> rootItem = new TreeItem<>(new PathRef("", Paths.get("data")));
    rootItem.setExpanded(true);
    payloadTreeView.setRoot(rootItem);
    payloadTreeView.setOnDragOver(event -> {
        if (event.getGestureSource() != payloadTreeView && event.getDragboard().getFiles().size() > 0) {
            event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
        }
        event.consume();
    });
    payloadTreeView.setOnDragDropped(event -> {
        Dragboard db = event.getDragboard();
        boolean success = false;
        if (db.getFiles().size() > 0) {
            for (File dragFile : db.getFiles()) {
                if (dragFile.isDirectory()) {
                    // explode directory and add expanded relative paths to tree
                    relPathSB = new StringBuilder();
                    try {
                        Files.walkFileTree(dragFile.toPath(), new SimpleFileVisitor<Path>() {
                            @Override
                            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                                    throws IOException {
                                relPathSB.append(dir.getFileName()).append("/");
                                return FileVisitResult.CONTINUE;
                            }

                            @Override
                            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                                    throws IOException {
                                payloadTreeView.getRoot().getChildren()
                                        .add(new TreeItem<>(new PathRef(relPathSB.toString(), file)));
                                bagSize += Files.size(file);
                                return FileVisitResult.CONTINUE;
                            }
                        });
                    } catch (IOException ioe) {
                    }
                } else {
                    payloadTreeView.getRoot().getChildren()
                            .add(new TreeItem<>(new PathRef("", dragFile.toPath())));
                    bagSize += dragFile.length();
                }
            }
            bagSizeLabel.setText(scaledSize(bagSize, 0));
            success = true;
            updateButtons();
        }
        event.setDropCompleted(success);
        event.consume();
    });

    metadataPropertySheet.setModeSwitcherVisible(false);
    metadataPropertySheet.setDisable(false);
    metadataPropertySheet.addEventHandler(KeyEvent.ANY, event -> {
        checkComplete(metadataPropertySheet.getItems());
        event.consume();
    });
}

From source file:net.rptools.tokentool.controller.ManageOverlays_Controller.java

public void displayTreeView() {
    TreeItem<Path> root = new OverlayTreeItem(AppConstants.OVERLAY_DIR);
    root.setExpanded(true);
    overlayTreeView.setRoot(root);//from  w ww .  j  av  a  2 s . c  o  m

    overlayTreeView.setCellFactory(treeView -> new TreeCell<Path>() {
        @Override
        public void updateItem(Path path, boolean empty) {
            super.updateItem(path, empty);
            if (empty) {
                setText(null);
            } else {
                setText(path.getFileName().toString());
            }
        }
    });
}

From source file:org.dataconservancy.packaging.gui.presenter.impl.EditPackageContentsPresenterImplTest.java

/**
 * Helper function for getting a child with a given ID
 * @param parent the parent TreeItem/*from w  w w.java2  s  . co m*/
 * @param id the ID
 * @return  a child with a given ID
 */
private TreeItem<Node> findChild(TreeItem<Node> parent, URI id) {
    for (TreeItem<Node> ti : parent.getChildren()) {
        if (ti.getValue().getIdentifier().equals(id)) {
            parent.setExpanded(true);
            return ti;
        }
    }

    return null;
}

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)/* w  w  w .  ja va 2  s .  com*/
                        .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: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);
        } else if (!item.isExpanded() && expand) {
            item.setExpanded(expand);//from  w w  w .j  a v  a  2s.co m
        }

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

From source file:jduagui.Controller.java

private TreeItem<File> buildFileTree(String path) throws IOException {
    File f = new File(path);
    TreeItem<File> root = createNode(f);
    root.setExpanded(true);
    root.setGraphic(new ImageView(new Image(getClass().getResourceAsStream("/16x16/apps/gnome-disks.png"))));
    return root;//from  www  .  j a  v a2 s.c o m
}