Example usage for javax.swing.tree DefaultMutableTreeNode getPath

List of usage examples for javax.swing.tree DefaultMutableTreeNode getPath

Introduction

In this page you can find the example usage for javax.swing.tree DefaultMutableTreeNode getPath.

Prototype

public TreeNode[] getPath() 

Source Link

Document

Returns the path from the root, to get to this node.

Usage

From source file:com.pironet.tda.TDA.java

/**
 * navigate to the currently selected dump in logfile
 *//*  w  ww  .  ja  v a2 s  .  com*/
private void navigateToDumpInLogfile() {
    Object userObject = ((DefaultMutableTreeNode) tree.getSelectionPath().getLastPathComponent())
            .getUserObject();
    if (userObject instanceof ThreadDumpInfo) {
        ThreadDumpInfo ti = (ThreadDumpInfo) userObject;
        int lineNumber = ti.getLogLine();

        // find log file node.
        TreePath selPath = tree.getSelectionPath();
        while (selPath != null && !checkNameFromNode((DefaultMutableTreeNode) selPath.getLastPathComponent(),
                File.separator)) {

            selPath = selPath.getParentPath();
        }

        tree.setSelectionPath(selPath);
        tree.scrollPathToVisible(selPath);
        if (selPath == null) {
            return;
        }

        Enumeration childs = ((DefaultMutableTreeNode) selPath.getLastPathComponent()).children();
        boolean found = false;
        DefaultMutableTreeNode logfileContent = null;
        while (!found && childs.hasMoreElements()) {
            logfileContent = (DefaultMutableTreeNode) childs.nextElement();
            found = logfileContent.getUserObject() instanceof LogFileContent;
        }

        if (found) {
            TreePath monitorPath = new TreePath(logfileContent.getPath());
            tree.setSelectionPath(monitorPath);
            tree.scrollPathToVisible(monitorPath);
            displayLogFileContent(logfileContent.getUserObject());
            jeditPane.setFirstLine(lineNumber - 1);
        }
    }
}

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   ww  w.  j a  va  2 s.c om*/
    }

    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:edu.harvard.i2b2.query.ui.QueryConceptTreePanel.java

private List getConceptsFromTerm(QueryConceptTreeNodeData data, DefaultMutableTreeNode tmpnode) {

    //      QueryConceptTreeNodeData data = (QueryConceptTreeNodeData) node.getUserObject();
    try {/*from  w w  w.j  ava 2 s .  co  m*/
        GetTermInfoType parentType = new GetTermInfoType();

        parentType.setMax(null);//Integer.parseInt(System.getProperty("OntMax")));
        parentType.setHiddens(Boolean.parseBoolean(System.getProperty("OntHiddens")));
        parentType.setSynonyms(Boolean.parseBoolean(System.getProperty("OntSynonyms")));

        parentType.setMax(parentPanel.max_child());

        parentType.setBlob(true);

        parentType.setSelf(data.fullname());
        GetChildrenResponseMessage msg = new GetChildrenResponseMessage();
        StatusType procStatus = null;
        String response = OntServiceDriver.getTermInfo(parentType, "");
        procStatus = msg.processResult(response);
        int result;
        if (procStatus.getValue().equals("MAX_EXCEEDED") && tmpnode != null) {
            result = JOptionPane.showConfirmDialog(parentPanel,
                    "The node has exceeded maximum number of children.\n" + "Do you want to continue?",
                    "Please note ...", JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.NO_OPTION) {
                //DefaultMutableTreeNode tmpnode = data;//(DefaultMutableTreeNode) node.getChildAt(0);
                QueryConceptTreeNodeData tmpdata = (QueryConceptTreeNodeData) tmpnode.getUserObject();
                tmpdata.name("Over maximum number of child nodes");
                //procStatus.setType("DONE");
                jTree1.repaint();
                jTree1.scrollPathToVisible(new TreePath(tmpnode.getPath()));
                return null;
            } else {
                parentType.setMax(null);
                response = OntServiceDriver.getTermInfo(parentType, "");
                procStatus = msg.processResult(response);
            }
        }

        if (!procStatus.getType().equals("DONE")) {
            JOptionPane.showMessageDialog(parentPanel, "Error message delivered from the remote server, "
                    + "you may wish to retry your last action");
            return null;
        }

        ConceptsType allConcepts = msg.doReadConcepts();
        return allConcepts.getConcept();

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(parentPanel,
                "Response delivered from the remote server could not be understood,\n"
                        + "you may wish to retry your last action.");
        return null;
    }
}

From source file:edu.harvard.i2b2.query.ui.QueryConceptTreePanel.java

private List getConceptsFromChildren(QueryConceptTreeNodeData data, DefaultMutableTreeNode tmpnode) {

    //      QueryConceptTreeNodeData data = (QueryConceptTreeNodeData) node.getUserObject();
    try {//from   w ww .  ja v a 2  s  .c o  m
        GetChildrenType parentType = new GetChildrenType();

        parentType.setMax(null);//Integer.parseInt(System.getProperty("OntMax")));
        parentType.setHiddens(Boolean.parseBoolean(System.getProperty("OntHiddens")));
        parentType.setSynonyms(Boolean.parseBoolean(System.getProperty("OntSynonyms")));

        parentType.setMax(parentPanel.max_child());

        parentType.setBlob(true);

        parentType.setParent(data.fullname());
        GetChildrenResponseMessage msg = new GetChildrenResponseMessage();
        StatusType procStatus = null;
        String response = OntServiceDriver.getChildren(parentType, "");
        procStatus = msg.processResult(response);
        int result;
        if (procStatus.getValue().equals("MAX_EXCEEDED") && tmpnode != null) {
            result = JOptionPane.showConfirmDialog(parentPanel,
                    "The node has exceeded maximum number of children.\n" + "Do you want to continue?",
                    "Please note ...", JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.NO_OPTION) {
                //DefaultMutableTreeNode tmpnode = data;//(DefaultMutableTreeNode) node.getChildAt(0);
                QueryConceptTreeNodeData tmpdata = (QueryConceptTreeNodeData) tmpnode.getUserObject();
                tmpdata.name("Over maximum number of child nodes");
                //procStatus.setType("DONE");
                jTree1.repaint();
                jTree1.scrollPathToVisible(new TreePath(tmpnode.getPath()));
                return null;
            } else {
                parentType.setMax(null);
                response = OntServiceDriver.getChildren(parentType, "");
                procStatus = msg.processResult(response);
            }
        }

        if (!procStatus.getType().equals("DONE")) {
            JOptionPane.showMessageDialog(parentPanel, "Error message delivered from the remote server, "
                    + "you may wish to retry your last action");
            return null;
        }

        ConceptsType allConcepts = msg.doReadConcepts();
        return allConcepts.getConcept();

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(parentPanel,
                "Response delivered from the remote server could not be understood,\n"
                        + "you may wish to retry your last action.");
        return null;
    }
}

From source file:edu.harvard.i2b2.query.ui.ConceptTreePanel.java

private List getConceptsFromTerm(QueryConceptTreeNodeData data, DefaultMutableTreeNode tmpnode) {

    // QueryConceptTreeNodeData data = (QueryConceptTreeNodeData)
    // node.getUserObject();
    try {//from w  w w .  ja v a  2s .  com
        GetTermInfoType parentType = new GetTermInfoType();

        parentType.setMax(null);// Integer.parseInt(System.getProperty(
        // "OntMax")));
        parentType.setHiddens(Boolean.parseBoolean(System.getProperty("OntHiddens")));
        parentType.setSynonyms(Boolean.parseBoolean(System.getProperty("OntSynonyms")));

        parentType.setMax(parentPanel.max_child());

        parentType.setBlob(true);

        parentType.setSelf(data.fullname());
        GetChildrenResponseMessage msg = new GetChildrenResponseMessage();
        StatusType procStatus = null;
        String response = OntServiceDriver.getTermInfo(parentType, "");
        procStatus = msg.processResult(response);
        int result;
        if (procStatus.getValue().equals("MAX_EXCEEDED") && tmpnode != null) {
            result = JOptionPane.showConfirmDialog(parentPanel,
                    "The node has exceeded maximum number of children.\n" + "Do you want to continue?",
                    "Please note ...", JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.NO_OPTION) {
                // DefaultMutableTreeNode tmpnode =
                // data;//(DefaultMutableTreeNode) node.getChildAt(0);
                QueryConceptTreeNodeData tmpdata = (QueryConceptTreeNodeData) tmpnode.getUserObject();
                tmpdata.name("Over maximum number of child nodes");
                // procStatus.setType("DONE");
                jTree1.repaint();
                jTree1.scrollPathToVisible(new TreePath(tmpnode.getPath()));
                return null;
            } else {
                parentType.setMax(null);
                response = OntServiceDriver.getTermInfo(parentType, "");
                procStatus = msg.processResult(response);
            }
        }

        if (!procStatus.getType().equals("DONE")) {
            JOptionPane.showMessageDialog(parentPanel, "Error message delivered from the remote server, "
                    + "you may wish to retry your last action");
            return null;
        }

        ConceptsType allConcepts = msg.doReadConcepts();
        return allConcepts.getConcept();

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(parentPanel,
                "Response delivered from the remote server could not be understood,\n"
                        + "you may wish to retry your last action.");
        return null;
    }
}

From source file:edu.harvard.i2b2.query.ui.ConceptTreePanel.java

private List getConceptsFromChildren(QueryConceptTreeNodeData data, DefaultMutableTreeNode tmpnode) {

    // QueryConceptTreeNodeData data = (QueryConceptTreeNodeData)
    // node.getUserObject();
    try {//from   www .  jav a 2 s.c  om
        GetChildrenType parentType = new GetChildrenType();

        parentType.setMax(null);// Integer.parseInt(System.getProperty(
        // "OntMax")));
        parentType.setHiddens(Boolean.parseBoolean(System.getProperty("OntHiddens")));
        parentType.setSynonyms(Boolean.parseBoolean(System.getProperty("OntSynonyms")));

        parentType.setMax(parentPanel.max_child());

        parentType.setBlob(true);

        parentType.setParent(data.fullname());
        GetChildrenResponseMessage msg = new GetChildrenResponseMessage();
        StatusType procStatus = null;
        String response = OntServiceDriver.getChildren(parentType, "");
        procStatus = msg.processResult(response);
        int result;
        if (procStatus.getValue().equals("MAX_EXCEEDED") && tmpnode != null) {
            result = JOptionPane.showConfirmDialog(parentPanel,
                    "The node has exceeded maximum number of children.\n" + "Do you want to continue?",
                    "Please note ...", JOptionPane.YES_NO_OPTION);

            if (result == JOptionPane.NO_OPTION) {
                // DefaultMutableTreeNode tmpnode =
                // data;//(DefaultMutableTreeNode) node.getChildAt(0);
                QueryConceptTreeNodeData tmpdata = (QueryConceptTreeNodeData) tmpnode.getUserObject();
                tmpdata.name("Over maximum number of child nodes");
                // procStatus.setType("DONE");
                jTree1.repaint();
                jTree1.scrollPathToVisible(new TreePath(tmpnode.getPath()));
                return null;
            } else {
                parentType.setMax(null);
                response = OntServiceDriver.getChildren(parentType, "");
                procStatus = msg.processResult(response);
            }
        }

        if (!procStatus.getType().equals("DONE")) {
            JOptionPane.showMessageDialog(parentPanel, "Error message delivered from the remote server, "
                    + "you may wish to retry your last action");
            return null;
        }

        ConceptsType allConcepts = msg.doReadConcepts();
        return allConcepts.getConcept();

    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(parentPanel,
                "Response delivered from the remote server could not be understood,\n"
                        + "you may wish to retry your last action.");
        return null;
    }
}

From source file:com.pironet.tda.TDA.java

/**
 * navigate to monitor/*  w ww .ja  va2  s . c om*/
 *
 * @param monitorLink the monitor link to navigate to
 */
private void navigateToMonitor(String monitorLink) {
    String monitor = monitorLink.substring(monitorLink.lastIndexOf('/') + 1);

    // find monitor node for this thread info
    DefaultMutableTreeNode dumpNode;
    if (monitorLink.indexOf("Dump No.") > 0) {
        dumpNode = getDumpRootNode(
                monitorLink.substring(monitorLink.indexOf('/') + 1, monitorLink.lastIndexOf('/')),
                (DefaultMutableTreeNode) tree.getLastSelectedPathComponent());
    } else {
        dumpNode = getDumpRootNode((DefaultMutableTreeNode) tree.getLastSelectedPathComponent());
    }
    final Enumeration children = dumpNode.children();
    DefaultMutableTreeNode monitorNode = null;
    DefaultMutableTreeNode monitorWithoutLocksNode = null;
    while (children.hasMoreElements()) {
        DefaultMutableTreeNode child = (DefaultMutableTreeNode) children.nextElement();
        if (child.getUserObject() instanceof TreeCategory) {
            if (((TreeCategory) child.getUserObject()).getName().startsWith("Monitors (")) {
                monitorNode = child;
            } else if (((TreeCategory) child.getUserObject()).getName().startsWith("Monitors without")) {
                monitorWithoutLocksNode = child;
            }
        }
    }

    // highlight chosen monitor
    JTree searchTree = (JTree) ((TreeCategory) monitorNode.getUserObject()).getCatComponent(this);
    TreePath searchPath = searchTree.getNextMatch(monitor, 0, Position.Bias.Forward);
    if ((searchPath == null) && (monitorWithoutLocksNode != null)) {
        searchTree = (JTree) ((TreeCategory) monitorWithoutLocksNode.getUserObject()).getCatComponent(this);
        searchPath = searchTree.getNextMatch(monitor, 0, Position.Bias.Forward);
        monitorNode = monitorWithoutLocksNode;
    }

    if (searchPath != null) {
        TreePath monitorPath = new TreePath(monitorNode.getPath());
        tree.setSelectionPath(monitorPath);
        tree.scrollPathToVisible(monitorPath);

        displayCategory(monitorNode.getUserObject());

        TreePath threadInMonitor = searchPath
                .pathByAddingChild(((DefaultMutableTreeNode) searchPath.getLastPathComponent()).getLastChild());
        searchTree.setSelectionPath(threadInMonitor);
        searchTree.scrollPathToVisible(searchPath);
        searchTree.setSelectionPath(searchPath);
    }
}

From source file:edu.harvard.i2b2.previousquery.QueryPreviousRunsPanel.java

private void populateChildNodes(DefaultMutableTreeNode node) {
    if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryMasterData")) {
        QueryMasterData data = (QueryMasterData) node.getUserObject();
        try {/*from   ww  w  .j av a  2s  .  c o  m*/
            String xmlRequest = data.writeContentQueryXML();
            lastRequestMessage = xmlRequest;
            //System.out.println(xmlRequest);
            String xmlResponse = QueryListNamesClient.sendQueryRequestREST(xmlRequest);
            if (xmlResponse.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                return;
            }
            lastResponseMessage = xmlResponse;

            try {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();
                JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlResponse);
                ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();

                BodyType bt = messageType.getMessageBody();
                InstanceResponseType instanceResponseType = (InstanceResponseType) new JAXBUnWrapHelper()
                        .getObjectByClass(bt.getAny(), InstanceResponseType.class);

                for (QueryInstanceType queryInstanceType : instanceResponseType.getQueryInstance()) {
                    //change later for working with new xml schema
                    //RunQuery runQuery = queryInstanceType.getResult().get(i).getRunQuery().get(0);

                    QueryInstanceData runData = new QueryInstanceData();

                    runData.visualAttribute("FA");
                    runData.tooltip("The results of the query run");
                    runData.id(new Integer(queryInstanceType.getQueryInstanceId()).toString());
                    //runData.patientRefId(new Integer(queryInstanceType.getRefId()).toString());
                    //runData.patientCount(new Long(queryInstanceType.getCount()).toString());
                    XMLGregorianCalendar cldr = queryInstanceType.getStartDate();
                    runData.name("Results of " + "[" + addZero(cldr.getMonth()) + "-" + addZero(cldr.getDay())
                            + "-" + addZero(cldr.getYear()) + " " + addZero(cldr.getHour()) + ":"
                            + addZero(cldr.getMinute()) + ":" + addZero(cldr.getSecond()) + "]");

                    data.runs.add(runData);
                    addNode(runData, node);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            jTree1.scrollPathToVisible(new TreePath(node.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryInstanceData")) {
        QueryInstanceData data = (QueryInstanceData) node.getUserObject();

        try {
            String xmlRequest = data.writeContentQueryXML();
            lastRequestMessage = xmlRequest;
            //System.out.println(xmlRequest);

            String xmlResponse = QueryListNamesClient.sendQueryRequestREST(xmlRequest);
            if (xmlResponse.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                return;
            }
            lastResponseMessage = xmlResponse;

            JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

            JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlResponse);
            ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
            BodyType bt = messageType.getMessageBody();
            ResultResponseType resultResponseType = (ResultResponseType) new JAXBUnWrapHelper()
                    .getObjectByClass(bt.getAny(), ResultResponseType.class);

            for (QueryResultInstanceType queryResultInstanceType : resultResponseType
                    .getQueryResultInstance()) {
                String status = queryResultInstanceType.getQueryStatusType().getName();

                QueryResultData resultData = new QueryResultData();
                resultData.visualAttribute("LAO");
                resultData.tooltip("A patient set of the query run");
                //resultData.queryId(data.queryId());
                resultData.patientRefId(new Integer(queryResultInstanceType.getResultInstanceId()).toString());//data.patientRefId());
                resultData.patientCount(new Integer(queryResultInstanceType.getSetSize()).toString());//data.patientCount());
                if (status.equalsIgnoreCase("FINISHED")) {
                    resultData.name("Patient Set - " + resultData.patientCount() + " Patients");
                } else {
                    resultData.name("Patient Set - " + status);
                }
                resultData.xmlContent(xmlResponse);

                addNode(resultData, node);
            }

            jTree1.scrollPathToVisible(new TreePath(node.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //implement for other type of nodes later!!!
}

From source file:com.mindcognition.mindraider.ui.swing.trash.TrashJPanel.java

/**
 * Constructor./*w  ww .j  a  va2 s. c o  m*/
 */
private TrashJPanel() {
    treeNodeToResourceUriMap = new HashMap();

    rootNode = new DefaultMutableTreeNode(Messages.getString("TrashJPanel.notebookArchive"));
    treeModel = new DefaultTreeModel(rootNode);
    treeModel.addTreeModelListener(new MyTreeModelListener());

    tree = new JTree(treeModel);
    tree.setEditable(false);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.addTreeExpansionListener(this);
    tree.addTreeWillExpandListener(this);
    tree.setShowsRootHandles(true);
    tree.putClientProperty("JTree.lineStyle", "Angled");

    // tree rendered
    // TODO implement own renderer in order to tooltips
    tree.setCellRenderer(new TrashTreeCellRenderer(IconsRegistry.getImageIcon("trashFull.png"),
            IconsRegistry.getImageIcon("explorerNotebookIcon.png")));

    setLayout(new BorderLayout());

    // control panel
    JToolBar tp = new JToolBar();
    tp.setLayout(new GridLayout(1, 6));
    undoButton = new JButton("", IconsRegistry.getImageIcon("trashUndo.png"));
    undoButton.setEnabled(false);
    undoButton.setToolTipText("Restore Outline");
    undoButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }
            new RestoreNotebookJDialog((String) treeNodeToResourceUriMap.get(node), "Restore Outline",
                    "Restore", true);
        }
    });
    tp.add(undoButton);

    deleteButton = new JButton("", IconsRegistry.getImageIcon("explorerDeleteSmall.png"));
    deleteButton.setToolTipText("Delete Outline");
    deleteButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }

            int result = JOptionPane.showConfirmDialog(MindRaider.mainJFrame,
                    "Do you really want to DELETE this Outline?", "Delete Outline", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                MindRaider.labelCustodian.deleteOutline((String) treeNodeToResourceUriMap.get(node));
                refresh();
                ExplorerJPanel.getInstance().refresh();
            }
        }
    });
    tp.add(deleteButton);

    emptyButton = new JButton("", IconsRegistry.getImageIcon("trashEmpty.png"));

    emptyButton.setToolTipText(Messages.getString("TrashJPanel.emptyArchive"));
    emptyButton.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int result = JOptionPane.showConfirmDialog(MindRaider.mainJFrame,
                    "Do you really want to DELETE all discarded Outlines?", "Empty Trash",
                    JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.YES_OPTION) {
                final SwingWorker worker = new SwingWorker() {

                    public Object construct() {
                        ProgressDialogJFrame progressDialogJFrame = new ProgressDialogJFrame("Empty Trash",
                                "<html><br>&nbsp;&nbsp;<b>Deleting:</b>&nbsp;&nbsp;</html>");
                        try {
                            ResourceDescriptor[] resourceDescriptors = MindRaider.labelCustodian
                                    .getDiscardedOutlineDescriptors();
                            if (resourceDescriptors != null) {
                                for (int i = 0; i < resourceDescriptors.length; i++) {
                                    MindRaider.labelCustodian.deleteOutline(resourceDescriptors[i].getUri());
                                }
                                refresh();
                            }
                        } finally {
                            if (progressDialogJFrame != null) {
                                progressDialogJFrame.dispose();
                            }
                        }
                        return null;
                    }
                };
                worker.start();
            }
        }
    });
    tp.add(emptyButton);

    add(tp, BorderLayout.NORTH);

    // add the tree
    JScrollPane scrollPane = new JScrollPane(tree);
    add(scrollPane);
    // build the whole tree
    buildTree();
    // click handler
    tree.addTreeSelectionListener(new TreeSelectionListener() {

        public void valueChanged(TreeSelectionEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            if (node == null) {
                return;
            }
            logger.debug("Tree selection path: " + node.getPath()[node.getLevel()]);

            enableDisableToolbarButtons(node.getLevel());
        }
    });
}

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);//w ww . j  a  v  a 2  s .c o 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;
}