Example usage for javax.swing.tree DefaultTreeModel removeNodeFromParent

List of usage examples for javax.swing.tree DefaultTreeModel removeNodeFromParent

Introduction

In this page you can find the example usage for javax.swing.tree DefaultTreeModel removeNodeFromParent.

Prototype

public void removeNodeFromParent(MutableTreeNode node) 

Source Link

Document

Message this to remove node from its parent.

Usage

From source file:TreeNodeRemove.java

public static void main(String[] argv) {
    Vector<String> v = new Vector<String>();
    v.add("a");//  w  ww.  j a  v  a 2s  .  c om
    v.add("b");
    v.add("c");
    JTree tree = new JTree(v);
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

    int startRow = 0;
    String prefix = "b";
    TreePath path = tree.getNextMatch(prefix, startRow, Position.Bias.Forward);
    MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();

    model.removeNodeFromParent(node);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new JScrollPane(tree));
    frame.setSize(380, 320);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

From source file:Main.java

protected void deleteSelectedItems() {
    DefaultMutableTreeNode node;/*from  w  w  w.j  a  v  a 2  s .  c  om*/
    DefaultTreeModel model = (DefaultTreeModel) (tree.getModel());
    TreePath[] paths = tree.getSelectionPaths();
    for (int i = 0; i < paths.length; i++) {
        node = (DefaultMutableTreeNode) (paths[i].getLastPathComponent());
        model.removeNodeFromParent(node);
    }
}

From source file:it.unibas.spicygui.controllo.window.operator.ProjectTreeGenerator.java

private boolean analisiRicorsivaCancellaScenario(Object root, Scenario scenario, DefaultTreeModel model) {
    int indice = model.getChildCount(root);
    //        if (indice == 1 || indice == 2) {
    TreeTopComponentAdapter componentAdapter = (TreeTopComponentAdapter) ((DefaultMutableTreeNode) root)
            .getUserObject();// w  w w.ja  va 2  s.  co m
    TopComponent tc = componentAdapter.getTopComponent();
    if (tc != null && tc == scenario.getMappingTaskTopComponent()) {
        TreeNode treeNode = (TreeNode) root;
        model.removeNodeFromParent((MutableTreeNode) treeNode.getParent());
        return false;
    }
    //        }

    for (int i = 0; i < indice; i++) {
        if (!analisiRicorsivaCancellaScenario(model.getChild(root, i), scenario, model)) {
            return false;
        }
    }
    return true;

    //        for (int i = 0; i < root.getChildCount(); i++) {
    //            TreePath treePath = jTree.getPathForRow(i);
    //            TreeNode treeNode = (TreeNode) treePath.getLastPathComponent();
    //            TreeTopComponentAdapter componentAdapter = (TreeTopComponentAdapter) ((DefaultMutableTreeNode) treeNode).getUserObject();
    //            TopComponent tc = componentAdapter.getTopComponent();
    //            if (tc != null && tc == scenario.getMappingTaskTopComponent()) {
    //                int place = model.getChildCount(treeNode.getParent());
    //                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new TreeTopComponentAdapter(topComponentAdded, false, false));
    //                model.insertNodeInto(newNode, (DefaultMutableTreeNode) treeNode.getParent(), place);
    //                model.reload();
    //                break;
    //            }
    //        }
}

From source file:net.sf.jabref.gui.FindUnlinkedFilesDialog.java

/**
 * Creates a list of {@link File}s for all leaf nodes in the tree structure
 * <code>node</code>, which have been marked as <i>selected</i>. <br>
 * <br>//from ww  w. ja v  a 2s.c o m
 * <code>Selected</code> nodes correspond to those entries in the tree,
 * whose checkbox is <code>checked</code>.
 *
 * SIDE EFFECT: The checked nodes are removed from the tree.
 *
 * @param node
 *            The root node representing a tree structure.
 * @return A list of files of all checked leaf nodes.
 */
private List<File> getFileListFromNode(CheckableTreeNode node) {
    List<File> filesList = new ArrayList<>();
    Enumeration<CheckableTreeNode> children = node.depthFirstEnumeration();
    List<CheckableTreeNode> nodesToRemove = new ArrayList<>();
    for (CheckableTreeNode child : Collections.list(children)) {
        if (child.isLeaf() && child.isSelected()) {
            File nodeFile = ((FileNodeWrapper) child.getUserObject()).file;
            if ((nodeFile != null) && nodeFile.isFile()) {
                filesList.add(nodeFile);
                nodesToRemove.add(child);
            }
        }
    }

    // remove imported files from tree
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    for (CheckableTreeNode nodeToRemove : nodesToRemove) {
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode) nodeToRemove.getParent();
        model.removeNodeFromParent(nodeToRemove);

        // remove empty parent node
        while ((parent != null) && parent.isLeaf()) {
            DefaultMutableTreeNode pp = (DefaultMutableTreeNode) parent.getParent();
            if (pp != null) {
                model.removeNodeFromParent(parent);
            }
            parent = pp;
        }
        // TODO: update counter / see: getTreeCellRendererComponent for label generation
    }
    tree.invalidate();
    tree.repaint();

    return filesList;
}

From source file:edu.ku.brc.af.tasks.subpane.formeditor.ViewSetSelectorPanel.java

/**
 * Deletes a ForRow or a FormCell.//from w  ww . j  a  va2 s.c o m
 */
protected void delControl(final TYPE type) {
    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getSelectionModel().getSelectionPath()
            .getLastPathComponent();
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) selectedNode.getParent();
    Object formObj = selectedNode.getUserObject();

    // For when we select delete row Menu when on a Control
    if (type == TYPE.DelRow && formObj instanceof FormCell) {
        selectedNode = parentNode;
        parentNode = (DefaultMutableTreeNode) parentNode.getParent();
        formObj = selectedNode.getUserObject();
    }

    if (formObj instanceof FormRow) {
        FormRow row = (FormRow) formObj;
        ((FormViewDef) parentNode.getUserObject()).getRows().remove(row);
        for (FormCellIFace formCell : row.getCells()) {
            idHash.remove(formCell.getIdent());
        }

    } else if (formObj instanceof FormCell) {
        FormCell formCell = (FormCell) formObj;
        ((FormRow) parentNode.getUserObject()).getCells().remove(formCell);
        idHash.remove(formCell.getIdent());
    }

    renumberRows(formViewDef.getRows());
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

    model.removeNodeFromParent(selectedNode);
}

From source file:GUI.MainWindow.java

private void doDelete() {

    DefaultTreeModel dtm = (DefaultTreeModel) VulnTree.getModel();
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) dtm.getRoot();
    TreePath[] paths = VulnTree.getSelectionPaths();

    if (paths == null) {
        return;/*from   w  ww.  j  a  v a  2 s.co m*/
    }

    for (int i = 0; i < paths.length; i++) {
        TreePath path = paths[i];
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
        if (i == 0) {
            // This is the first delete operation
            DefaultMutableTreeNode previous = (DefaultMutableTreeNode) node.getPreviousSibling();
            // Consider saving deleted vulns into a scratchpad file TODO
            //System.out.println("previous:" + previous);

            // If it is null here we have no nodes above it, we get the next sibling below
            if (previous == null) {
                previous = (DefaultMutableTreeNode) node.getNextSibling();
            }

            // If it is still null here there are no nodes in the tree. Point to the root. Avoids NullPointerException
            if (previous == null) {
                previous = root;
            }

            TreePath p = new TreePath(previous.getPath());
            VulnTree.setSelectionPath(p);
        }

        if (node.getParent() != null) {
            dtm.removeNodeFromParent(node);
        }
    }

    if (root.getChildCount() == 0) {
        clearGUI();
    }

}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

private JPanel createAParameterBox(final boolean first) {

    final JLabel runLabel = new JLabel("<html><b>Number of runs:</b> 0</html>");
    final JLabel warningLabel = new JLabel();

    final JButton closeButton = new JButton();
    closeButton.setOpaque(false);//from  w w  w. j ava 2  s . co m
    closeButton.setBorder(null);
    closeButton.setFocusable(false);

    if (!first) {
        closeButton.setRolloverIcon(PARAMETER_BOX_REMOVE);
        closeButton.setRolloverEnabled(true);
        closeButton.setIcon(RGBGrayFilter.getDisabledIcon(closeButton, PARAMETER_BOX_REMOVE));
        closeButton.setActionCommand(ACTIONCOMMAND_REMOVE_BOX);
    }

    final JScrollPane treeScrPane = new JScrollPane();
    final DefaultMutableTreeNode treeRoot = new DefaultMutableTreeNode();
    final JTree tree = new JTree(treeRoot);
    ToolTipManager.sharedInstance().registerComponent(tree);

    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setCellRenderer(new ParameterBoxTreeRenderer());
    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(final TreeSelectionEvent e) {
            final TreePath selectionPath = tree.getSelectionPath();
            boolean success = true;
            if (editedNode != null
                    && (selectionPath == null || !editedNode.equals(selectionPath.getLastPathComponent())))
                success = modify();

            if (success) {
                if (selectionPath != null) {
                    cancelAllSelectionBut(tree);
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
                            .getLastPathComponent();
                    if (!node.equals(editedNode)) {
                        ParameterInATree userObj = null;
                        final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
                        if (!node.isRoot()
                                && selectionPath.getPathCount() == model.getPathToRoot(node).length) {
                            userObj = (ParameterInATree) node.getUserObject();
                            final ParameterInfo info = userObj.info;
                            editedNode = node;
                            editedTree = tree;
                            edit(info);
                        } else {
                            tree.setSelectionPath(null);
                            if (cancelButton.isEnabled())
                                cancelButton.doClick();
                            resetSettings();
                            enableDisableSettings(false);
                            editedNode = null;
                            editedTree = null;
                        }

                        updateDescriptionField(userObj);
                    } else
                        updateDescriptionField();

                } else
                    updateDescriptionField();

                enableDisableParameterCombinationButtons();
            } else {
                final DefaultTreeModel model = (DefaultTreeModel) editedTree.getModel();
                final DefaultMutableTreeNode storedEditedNode = editedNode;
                editedNode = null;
                tree.setSelectionPath(null);
                editedNode = storedEditedNode;
                editedTree.setSelectionPath(new TreePath(model.getPathToRoot(editedNode)));
            }
        }
    });

    treeScrPane.setViewportView(tree);
    treeScrPane.setBorder(null);
    treeScrPane.setViewportBorder(null);
    treeScrPane.setPreferredSize(new Dimension(450, 250));

    final JButton upButton = new JButton();
    upButton.setOpaque(false);
    upButton.setRolloverEnabled(true);
    upButton.setIcon(PARAMETER_UP_ICON);
    upButton.setRolloverIcon(PARAMETER_UP_ICON_RO);
    upButton.setDisabledIcon(PARAMETER_UP_ICON_DIS);
    upButton.setBorder(null);
    upButton.setToolTipText("Move up the selected parameter");
    upButton.setActionCommand(ACTIONCOMMAND_MOVE_UP);

    final JButton downButton = new JButton();
    downButton.setOpaque(false);
    downButton.setRolloverEnabled(true);
    downButton.setIcon(PARAMETER_DOWN_ICON);
    downButton.setRolloverIcon(PARAMETER_DOWN_ICON_RO);
    downButton.setDisabledIcon(PARAMETER_DOWN_ICON_DIS);
    downButton.setBorder(null);
    downButton.setToolTipText("Move down the selected parameter");
    downButton.setActionCommand(ACTIONCOMMAND_MOVE_DOWN);

    final JPanel mainPanel = FormsUtils.build("~ f:p:g ~ p ~ r:p",
            "012||" + "333||" + "44_||" + "445||" + "446||" + "44_ f:p:g", runLabel, first ? "" : warningLabel,
            first ? warningLabel : closeButton, new FormsUtils.Separator(""), treeScrPane, upButton, downButton)
            .getPanel();

    mainPanel.setBorder(BorderFactory.createTitledBorder(""));

    final JButton addButton = new JButton();
    addButton.setOpaque(false);
    addButton.setRolloverEnabled(true);
    addButton.setIcon(PARAMETER_ADD_ICON);
    addButton.setRolloverIcon(PARAMETER_ADD_ICON_RO);
    addButton.setDisabledIcon(PARAMETER_ADD_ICON_DIS);
    addButton.setBorder(null);
    addButton.setToolTipText("Add selected parameter");
    addButton.setActionCommand(ACTIONCOMMAND_ADD_PARAM);

    final JButton removeButton = new JButton();
    removeButton.setOpaque(false);
    removeButton.setRolloverEnabled(true);
    removeButton.setIcon(PARAMETER_REMOVE_ICON);
    removeButton.setRolloverIcon(PARAMETER_REMOVE_ICON_RO);
    removeButton.setDisabledIcon(PARAMETER_REMOVE_ICON_DIS);
    removeButton.setBorder(null);
    removeButton.setToolTipText("Remove selected parameter");
    removeButton.setActionCommand(ACTIONCOMMAND_REMOVE_PARAM);

    final JPanel result = FormsUtils.build("p ~ f:p:g", "_0 f:p:g||" + "10 p ||" + "20 p||" + "_0 f:p:g",
            mainPanel, addButton, removeButton).getPanel();

    Style.registerCssClasses(result, Dashboard.CSS_CLASS_COMMON_PANEL);

    final ParameterCombinationGUI pcGUI = new ParameterCombinationGUI(tree, treeRoot, runLabel, warningLabel,
            addButton, removeButton, upButton, downButton);
    parameterTreeBranches.add(pcGUI);

    final ActionListener boxActionListener = new ActionListener() {

        //====================================================================================================
        // methods

        //----------------------------------------------------------------------------------------------------
        public void actionPerformed(final ActionEvent e) {
            final String cmd = e.getActionCommand();

            if (ACTIONCOMMAND_ADD_PARAM.equals(cmd))
                handleAddParameter(pcGUI);
            else if (ACTIONCOMMAND_REMOVE_PARAM.equals(cmd))
                handleRemoveParameter(tree);
            else if (ACTIONCOMMAND_REMOVE_BOX.equals(cmd))
                handleRemoveBox(tree);
            else if (ACTIONCOMMAND_MOVE_UP.equals(cmd))
                handleMoveUp();
            else if (ACTIONCOMMAND_MOVE_DOWN.equals(cmd))
                handleMoveDown();
        }

        //----------------------------------------------------------------------------------------------------
        private void handleAddParameter(final ParameterCombinationGUI pcGUI) {
            final Object[] selectedValues = parameterList.getSelectedValues();
            if (selectedValues != null && selectedValues.length > 0) {
                final AvailableParameter[] params = new AvailableParameter[selectedValues.length];
                System.arraycopy(selectedValues, 0, params, 0, selectedValues.length);
                addParameterToTree(params, pcGUI);
                enableDisableParameterCombinationButtons();
            }
        }

        //----------------------------------------------------------------------------------------------------
        private void handleRemoveParameter(final JTree tree) {
            final TreePath selectionPath = tree.getSelectionPath();
            if (selectionPath != null) {
                cancelButton.doClick();

                final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
                        .getLastPathComponent();
                if (!node.isRoot()) {
                    final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node.getParent();
                    if (parentNode.isRoot()) {
                        removeParameter(tree, node, parentNode);
                        enableDisableParameterCombinationButtons();
                    }
                }
            }
        }

        //----------------------------------------------------------------------------------------------------
        private void handleRemoveBox(final JTree tree) {
            final int answer = Utilities.askUser(dashboard, false, "Comfirmation",
                    "This operation deletes the combination.",
                    "All related parameter returns back to the list on the left side.", "Are you sure?");
            if (answer == 1) {
                final DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();

                if (tree.getSelectionCount() > 0) {
                    editedNode = null;
                    tree.setSelectionPath(null);
                    if (cancelButton.isEnabled())
                        cancelButton.doClick();
                }

                final DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeModel.getRoot();
                for (int i = 0; i < root.getChildCount(); ++i) {
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(i);
                    removeParameter(tree, node, root);
                }

                enableDisableParameterCombinationButtons();

                parameterTreeBranches.remove(pcGUI);
                combinationsPanel.remove(result);
                combinationsPanel.revalidate();

                updateNumberOfRuns();
            }
        }

        //----------------------------------------------------------------------------------------------------
        private void removeParameter(final JTree tree, final DefaultMutableTreeNode node,
                final DefaultMutableTreeNode parentNode) {
            final ParameterInATree userObj = (ParameterInATree) node.getUserObject();
            final ParameterInfo originalInfo = findOriginalInfo(userObj.info);
            if (originalInfo != null) {
                final DefaultListModel model = (DefaultListModel) parameterList.getModel();
                model.addElement(new AvailableParameter(originalInfo, currentModelHandler.getModelClass()));
                final DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
                treeModel.removeNodeFromParent(node);
                updateNumberOfRuns();
                tree.expandPath(new TreePath(treeModel.getPathToRoot(parentNode)));
            } else
                throw new IllegalStateException(
                        "Parameter " + userObj.info.getName() + " is not found in the model.");
        }

        //----------------------------------------------------------------------------------------------------
        private void handleMoveUp() {
            final TreePath selectionPath = tree.getSelectionPath();
            if (selectionPath != null) {
                boolean success = true;
                if (editedNode != null)
                    success = modify();

                if (success) {
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
                            .getLastPathComponent();
                    final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();

                    if (parent == null || parent.getFirstChild().equals(node)) {
                        tree.setSelectionPath(null); // we need this to preserve the state of the parameter settings panel
                        tree.setSelectionPath(new TreePath(node.getPath()));
                        return;
                    }

                    final int index = parent.getIndex(node);
                    final DefaultTreeModel treemodel = (DefaultTreeModel) tree.getModel();
                    treemodel.removeNodeFromParent(node);
                    treemodel.insertNodeInto(node, parent, index - 1);
                    tree.setSelectionPath(new TreePath(node.getPath()));
                }

            }
        }

        //----------------------------------------------------------------------------------------------------
        private void handleMoveDown() {
            final TreePath selectionPath = tree.getSelectionPath();
            if (selectionPath != null) {
                boolean success = true;
                if (editedNode != null)
                    success = modify();

                if (success) {
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath
                            .getLastPathComponent();
                    final DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();

                    if (parent == null || parent.getLastChild().equals(node)) {
                        tree.setSelectionPath(null); // we need this to preserve the state of the parameter settings panel
                        tree.setSelectionPath(new TreePath(node.getPath()));
                        return;
                    }

                    final int index = parent.getIndex(node);
                    final DefaultTreeModel treemodel = (DefaultTreeModel) tree.getModel();
                    treemodel.removeNodeFromParent(node);
                    treemodel.insertNodeInto(node, parent, index + 1);
                    tree.setSelectionPath(new TreePath(node.getPath()));
                }
            }
        }
    };

    GUIUtils.addActionListener(boxActionListener, closeButton, upButton, downButton, addButton, removeButton);

    result.setPreferredSize(new Dimension(500, 250));
    enableDisableParameterCombinationButtons();

    Style.apply(result, dashboard.getCssStyle());

    return result;
}

From source file:src.gui.ItSIMPLE.java

public void updateCloseProjectParallelTree(DefaultTreeModel treeModel, int index) {

    //Close the projects in the plan simulation problem tree
    ItTreeNode treeRoot = (ItTreeNode) treeModel.getRoot();
    treeModel.removeNodeFromParent((ItTreeNode) treeRoot.getChildAt(index));

}

From source file:src.gui.ItSIMPLE.java

public void updateDeleteDomainProjectParallelTree(DefaultTreeModel treeModel, ItTreeNode domain,
        ItTreeNode project) {//from   www  .j  av  a 2 s .  c  o  m

    ItTreeNode problemsTreeProject = (ItTreeNode) ((ItTreeNode) treeModel.getRoot())
            .getChildAt(treeRoot.getIndex(project));

    ItTreeNode problemsTreeDomain = null;
    // look for the domain in problems plan tree
    for (int i = 0; i < problemsTreeProject.getChildCount(); i++) {
        ItTreeNode child = (ItTreeNode) problemsTreeProject.getChildAt(i);
        if (child.getData() == domain.getData()) {
            problemsTreeDomain = child;
            break;
        }
    }

    if (problemsTreeDomain != null) {
        treeModel.removeNodeFromParent(problemsTreeDomain);
    }
}

From source file:src.gui.ItSIMPLE.java

public void updateDeleteProblemProjectParallelTree(DefaultTreeModel treeModel, ItTreeNode domain,
        ItTreeNode problem, ItTreeNode project) {

    ItTreeNode problemsTreeProject = (ItTreeNode) ((ItTreeNode) treeModel.getRoot())
            .getChildAt(treeRoot.getIndex(project));

    ItTreeNode problemsTreeDomain = null;
    // look for the domain in problems plan tree
    for (int i = 0; i < problemsTreeProject.getChildCount(); i++) {
        ItTreeNode child = (ItTreeNode) problemsTreeProject.getChildAt(i);
        if (child.getData() == domain.getData()) {
            problemsTreeDomain = child;//from w ww  . ja va  2 s. c om
            break;
        }
    }

    if (problemsTreeDomain != null) {

        ItTreeNode problemsTreeProblem = null;
        // look for the problem in problems plan tree
        for (int i = 0; i < problemsTreeDomain.getChildCount(); i++) {
            ItTreeNode child = (ItTreeNode) problemsTreeDomain.getChildAt(i);
            if (child.getData() == problem.getData()) {
                problemsTreeProblem = child;
                break;
            }
        }

        treeModel.removeNodeFromParent(problemsTreeProblem);
    }
}