Example usage for javafx.scene.control TreeItem getValue

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

Introduction

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

Prototype

public final T getValue() 

Source Link

Document

Returns the application-specific data represented by this TreeItem.

Usage

From source file:ca.wumbo.doommanager.client.controller.file.DoomFileController.java

/**
 * This is to be called when the user clicks on a new row, which means the
 * GUI should be updated by disposing of whatever is on the right (if it's
 * possible), and adding in the new view.
 * //from  ww  w.j  ava 2s  .  com
 * @param oldTreeItem
 *       The old tree item (null is allowed).
 * 
 * @param newTreeItem
 *       The new tree item (null is allowed).
 */
private void updateGUIFromEntrySelection(TreeItem<Entry> oldTreeItem, TreeItem<Entry> newTreeItem) {
    // We only care if a click causes a change in entries.
    if (oldTreeItem != newTreeItem) {
        // Check if we haven't saved yet, and if not... prompt the user.
        // TODO

        // If we're changing to a new entry, time to load a new Pane.
        if (newTreeItem != null) {
            // Load the new Node based on what the entry is, and place it on the right.
            EntryControllable entryControllable = newTreeItem.getValue().getNewController();
            entryControllable.setEntry(newTreeItem.getValue());

            // Clean up the right pane to assist the garbage collector.
            // TODO

            // Insert the root pane at the center.
            rightBorderPane.setCenter(entryControllable.getRootPane());
        } else {
            // If we're going to null, we should clear last element placed in the pane with a blank pane.
            rightBorderPane.setCenter(new BorderPane());
        }
    }
}

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 ww.  j  av a  2s. co m*/
    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:org.jevis.jeconfig.plugin.classes.ClassTree.java

public void fireEventExport(ObservableList<TreeItem<JEVisClass>> items) {

    FileChooser fileChooser = new FileChooser();
    fileChooser.setTitle("Save JEVisClasses to File");
    fileChooser.getExtensionFilters().addAll(new ExtensionFilter("JEVis Files", "*.jev"),
            new ExtensionFilter("All Files", "*.*"));

    DateTime now = DateTime.now();/*from  w w w.  j a va  2  s  . c  o m*/
    DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");
    if (items.size() > 1) {
        fileChooser.setInitialFileName("JEViClassExport_" + fmt.print(now) + ".jev");
    } else {
        try {
            fileChooser.setInitialFileName(items.get(0).getValue().getName() + "_" + fmt.print(now) + ".jev");
        } catch (JEVisException ex) {
            Logger.getLogger(ClassTree.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    File selectedFile = fileChooser.showSaveDialog(JEConfig.getStage());
    if (selectedFile != null) {
        List<JEVisClass> classes = new ArrayList<>();
        for (TreeItem<JEVisClass> item : items) {
            classes.add(item.getValue());
        }

        String extension = FilenameUtils.getExtension(selectedFile.getName());
        if (extension.isEmpty()) {
            selectedFile = new File(selectedFile.getAbsoluteFile() + ".jsv");
        }

        ClassExporter ce = new ClassExporter(selectedFile, classes);
        //            mainStage.display(selectedFile);
    }
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private MenuItem createAddMenu(String name, TreeView<Object> elements, TreeItem<Object> selected) {
    ListHolder listHolder = (ListHolder) selected.getValue();

    MenuItem add = new MenuItem(name);
    add.setOnAction(event -> {//w w  w .j  av  a 2  s.c  o  m
        Stream<ClassHolder> st = SubclassManager.getInstance().getClassWithAllSubclasses(listHolder.type)
                .stream().map(ClassHolder::new);
        List<ClassHolder> list = st.collect(Collectors.toList());

        Optional<ClassHolder> choice;

        if (list.size() == 1) {
            choice = Optional.of(list.get(0));
        } else {
            ChoiceDialog<ClassHolder> cd = new ChoiceDialog<>(list.get(0), list);
            cd.setTitle("Select class");
            cd.setHeaderText(null);
            choice = cd.showAndWait();
        }
        choice.ifPresent(toCreate -> {
            try {
                IOEntity obj = toCreate.clazz.newInstance();

                listHolder.list.add(obj);
                TreeItem<Object> treeItem = createTreeItem(obj);
                selected.getChildren().add(treeItem);
                elements.getSelectionModel().select(treeItem);
                elements.scrollTo(elements.getSelectionModel().getSelectedIndex());

                editor.getHistory().valueCreated(treeItemToScriptString(selected), toCreate.clazz);
            } catch (ReflectiveOperationException e) {
                log.log(Level.WARNING, String.format("Couldn't instantiate %s", toCreate.clazz.getName()), e);
                Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                        "Couldn't instantiate " + toCreate.clazz);
            }
        });
    });

    return add;
}

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);
                        }/*w  w w  .  ja  v  a 2  s .co m*/
                    });

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

From source file:jduagui.Controller.java

private ChangeListener setListener() {
    return new ChangeListener() {
        @Override/*  w  w  w .  j ava 2s. c  o m*/
        public void changed(ObservableValue observable, Object oldValue, Object newValue) {
            TreeItem<File> selectedItem = (TreeItem<File>) newValue;
            if (selectedItem.getValue().getAbsolutePath().equals(rootPath))
                selectedPath = rootPath;
            else if (selectedItem.getValue().isDirectory())
                selectedPath = selectedItem.getValue().getAbsolutePath();
            else if (selectedItem.getValue().isFile())
                selectedPath = selectedItem.getValue().getParent();
        }
    };
}

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

public ClassTree(JEVisDataSource ds) {
    super();//from w ww  . j  a  v a 2  s. com
    try {
        _ds = ds;

        _itemCache = new HashMap<>();
        _graphicCache = new HashMap<>();
        _itemChildren = new HashMap<>();

        JEVisClass root = new JEVisRootClass(ds);
        TreeItem<JEVisClass> rootItem = buildItem(root);

        setShowRoot(true);
        rootItem.setExpanded(true);

        getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        _editor.setTreeView(this);

        setCellFactory(new Callback<TreeView<JEVisClass>, TreeCell<JEVisClass>>() {

            //                @Override
            //                public TreeCell<JEVisClass> call(TreeView<JEVisClass> p) {
            //                    return new ClassCell();
            //                }
            @Override
            public TreeCell<JEVisClass> call(TreeView<JEVisClass> param) {
                return new TreeCell<JEVisClass>() {
                    //                        private ImageView imageView = new ImageView();

                    @Override
                    protected void updateItem(JEVisClass item, boolean empty) {
                        super.updateItem(item, empty);

                        if (!empty) {
                            ClassGraphic gc = getClassGraphic(item);

                            setContextMenu(gc.getContexMenu());
                            //                                setText(item);
                            setGraphic(gc.getGraphic());
                        } else {
                            setText(null);
                            setGraphic(null);
                        }
                    }
                };
            }
        });

        getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<JEVisClass>>() {

            @Override
            public void changed(ObservableValue<? extends TreeItem<JEVisClass>> ov, TreeItem<JEVisClass> t,
                    TreeItem<JEVisClass> t1) {
                try {
                    if (t1 != null) {
                        _editor.setJEVisClass(t1.getValue());
                    }
                } catch (Exception ex) {
                    System.out.println("Error while changing editor: " + ex);
                }

            }
        });

        addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler<KeyEvent>() {

            @Override
            public void handle(KeyEvent t) {
                if (t.getCode() == KeyCode.F2) {
                    System.out.println("F2 rename event");
                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            fireEventRename();
                        }
                    });

                } else if (t.getCode() == KeyCode.DELETE) {

                    fireDelete(getSelectionModel().getSelectedItem().getValue());
                }
            }

        });

        setId("objecttree");

        getStylesheets().add("/styles/Styles.css");
        setPrefWidth(500);

        setRoot(rootItem);
        setEditable(true);

    } catch (Exception ex) {
        //            Logger.getLogger(ObjectTree.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    }

}

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

private void deteleItemFromTree(final TreeItem<JEVisClass> item) {
    try {//from  w  w w  . j  a v  a2s  . co m
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                try {
                    String className = item.getValue().getName();

                    _itemCache.remove(className);

                    for (Map.Entry<TreeItem<JEVisClass>, ObservableList<TreeItem<JEVisClass>>> entry : _itemChildren
                            .entrySet()) {

                        if (entry.getValue().contains(item)) {
                            entry.getValue().remove(item);
                        }
                    }

                    getSelectionModel().select(item.getParent());

                    if (_graphicCache.containsKey(className)) {
                        _graphicCache.remove(className);
                    }

                    //                    parentItem.setExpanded(false);
                } catch (JEVisException ex) {
                    Logger.getLogger(ClassTree.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

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  ww  .  j  a v  a 2s . 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:org.jevis.jeconfig.plugin.classes.ClassTree.java

public void fireEventNew(TreeItem<JEVisClass> item) {
    try {//from w  ww  . j av a2 s.co m
        NewClassDialog dia = new NewClassDialog();

        JEVisClass currentClass = null;

        if (item != null) {
            currentClass = item.getValue();
        } else if (item == null && getSelectionModel().getSelectedItem() != null) {
            currentClass = getSelectionModel().getSelectedItem().getValue();
        } else if (currentClass != null && currentClass.getName().equals("Classes")) {
            currentClass = null;
        }

        if (currentClass != null && currentClass.getName().equals("Classes")) {
            currentClass = null;
        }

        if (dia.show(JEConfig.getStage(), currentClass, _ds) == NewClassDialog.Response.YES
                && dia.getClassName() != null && !dia.getClassName().equals("")) {

            JEVisClass newClass = _ds.buildClass(dia.getClassName());

            if (dia.getInheritance() != null && newClass != null) {
                newClass.setIcon(dia.getInheritance().getIcon());
                newClass.commit();
            }

            final TreeItem<JEVisClass> treeItem = buildItem(newClass);

            if (dia.getInheritance() != null) {

                //reload workaround, loading the relationship befor creation ein will execute the getFixedRelationships() function
                newClass.getRelationships();

                JEVisClassRelationship cr = RelationshipFactory.buildInheritance(dia.getInheritance(),
                        newClass);

                //                    newClass = null;
                //                    newClass = _ds.getJEVisClass(dia.getClassName());
                //                    System.out.println("fixfix: " + newClass.getName());
                getChildrenList(getObjectTreeItem(dia.getInheritance())).add(getObjectTreeItem(newClass));
            } else {
                getChildrenList(getObjectTreeItem(getRoot().getValue())).add(getObjectTreeItem(newClass));
            }

            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    getSelectionModel().select(treeItem);
                }
            });
        }

    } catch (JEVisException ex) {
        ex.printStackTrace();
        Logger.getLogger(ClassTree.class.getName()).log(Level.SEVERE, null, ex);
    }
}