Example usage for javax.swing.tree DefaultMutableTreeNode getUserObject

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

Introduction

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

Prototype

public Object getUserObject() 

Source Link

Document

Returns this node's user object.

Usage

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 {/*  www  .j a  va 2s.  c  om*/
            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:org.kuali.maven.plugins.externals.MojoHelper.java

public void updateBuildInfo(DefaultMutableTreeNode node, BuildTag buildTag, TagStyle tagStyle,
        int buildNumber) {
    Project project = (Project) node.getUserObject();
    project.setBuildTag(buildTag);// ww w  .j a v a 2  s . c  o m
    GAV oldGav = project.getGav();
    String newVersion = getNewVersion(oldGav.getVersion(), buildNumber, buildTag.getSourceRevision(), tagStyle);
    GAV newGav = new GAV();
    newGav.setGroupId(oldGav.getGroupId());
    newGav.setArtifactId(oldGav.getArtifactId());
    newGav.setVersion(newVersion);
    project.setNewGav(newGav);
    logger.info("GAV Update - [" + toString(oldGav) + "->" + newVersion + "]");
}

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

public void treeExpanded(TreeExpansionEvent event) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) event.getPath().getLastPathComponent();
    QueryData data = (QueryData) node.getUserObject();
    jTree1.scrollPathToVisible(new TreePath(node));

    System.out.println("Node expanded: " + data.name());

    if (data.visualAttribute().equals("FA")) {
        data.visualAttribute("FAO");
    } else if (data.visualAttribute().equals("CA")) {
        data.visualAttribute("CAO");
    }/*ww  w .ja v  a2s  .c  om*/

    // check to see if child is a placeholder ('working...')
    //   if so, make Web Service call to update children of node
    if (node.getChildCount() == 1) {
        final DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) node.getChildAt(0);
        if (((QueryData) node1.getUserObject()).visualAttribute().equals("LAO")
                && ((QueryData) node1.getUserObject()).name().equals("working ......")) {
            final DefaultMutableTreeNode anode = node;
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    populateChildNodes(anode);
                }
            });
        }
    } else {
        for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode anode = (DefaultMutableTreeNode) node.getChildAt(0);
            QueryData adata = (QueryData) anode.getUserObject();
            if (adata.visualAttribute().equals("FAO")) {
                adata.visualAttribute("FA");
            } else if (adata.visualAttribute().equals("CAO")) {
                adata.visualAttribute("CA");
            }
        }
    }
}

From source file:gdt.jgui.entity.JEntityDigestDisplay.java

private void select() {
    if (selection$ == null)
        return;//  w  ww . j  a v a2 s .  co m
    try {
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
        Enumeration en = root.preorderEnumeration();
        DefaultMutableTreeNode node;
        // System.out.println("EntityDigestDisplay:select:selection="+selection$);
        Properties locator = Locator.toProperties(selection$);
        String selectionNumber$ = locator.getProperty(NODE_NUMBER);
        //          System.out.println("EntityDigestDisplay:select:selection number="+selectionNumber$);
        String nodeLocator$;
        String nodeNumber$;
        while (en.hasMoreElements()) {
            node = (DefaultMutableTreeNode) en.nextElement();
            nodeLocator$ = (String) node.getUserObject();
            locator = Locator.toProperties(nodeLocator$);
            nodeNumber$ = locator.getProperty(NODE_NUMBER);
            //            System.out.println("EntityDigestDisplay:select:node number="+nodeNumber$);
            if (selectionNumber$.equals(nodeNumber$)) {
                TreeNode[] nodes = ((DefaultTreeModel) tree.getModel()).getPathToRoot(node);
                TreePath tpath = new TreePath(nodes);
                tree.scrollPathToVisible(tpath);
                tree.setSelectionPath(tpath);
                break;
            }
        }
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).severe(e.toString());
    }
}

From source file:org.kuali.maven.plugins.externals.MojoHelper.java

public void validateParents(DefaultMutableTreeNode node, Map<String, DefaultMutableTreeNode> map) {
    Enumeration<?> e = node.breadthFirstEnumeration();
    while (e.hasMoreElements()) {
        DefaultMutableTreeNode element = (DefaultMutableTreeNode) e.nextElement();
        if (element.isRoot()) {
            continue;
        }/*  w  w w  .  j  a  va2s  .com*/
        Project project = (Project) element.getUserObject();
        GAV parentGav = project.getParent();
        String parentGavId = toString(parentGav);
        DefaultMutableTreeNode parent = map.get(parentGavId);
        if (parent == null) {
            throw new IllegalStateException(parentGavId + " could not be located");
        }
    }
}

From source file:dotaSoundEditor.Controls.EditorPanel.java

protected File promptUserForNewFile(String wavePath) {
    JFileChooser chooser = new JFileChooser(new File(UserPrefs.getInstance().getWorkingDirectory()));
    FileNameExtensionFilter filter = new FileNameExtensionFilter("MP3s and WAVs", "mp3", "wav");
    chooser.setAcceptAllFileFilterUsed((false));
    chooser.setFileFilter(filter);/*from   w  w w.j  a v  a 2 s  .  co m*/
    chooser.setMultiSelectionEnabled(false);

    int chooserRetVal = chooser.showOpenDialog(chooser);
    if (chooserRetVal == JFileChooser.APPROVE_OPTION) {
        DefaultMutableTreeNode selectedFile = (DefaultMutableTreeNode) getTreeNodeFromWavePath(wavePath);
        Path chosenFile = Paths.get(chooser.getSelectedFile().getAbsolutePath());
        //Strip caps and spaces out of filenames. The item sound parser seems to have trouble with them.
        String destFileName = chosenFile.getFileName().toString().toLowerCase().replace(" ", "_");
        Path destPath = Paths.get(installDir, "/dota/sound/" + getCustomSoundPathString() + destFileName);
        UserPrefs.getInstance().setWorkingDirectory(chosenFile.getParent().toString());

        try {
            new File(destPath.toString()).mkdirs();
            Files.copy(chosenFile, destPath, StandardCopyOption.REPLACE_EXISTING);

            String waveString = selectedFile.getUserObject().toString();
            int startIndex = -1;
            int endIndex = -1;
            if (waveString.contains("\"wave\"")) {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 2);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 3);
            } else //Some wavestrings don't have the "wave" at the beginning for some reason
            {
                startIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 0);
                endIndex = Utility.nthOccurrence(selectedFile.getUserObject().toString(), '\"', 1);
            }

            String waveStringFilePath = waveString.substring(startIndex, endIndex + 1);
            waveString = waveString.replace(waveStringFilePath,
                    "\"" + getCustomSoundPathString() + destFileName + "\"");
            selectedFile.setUserObject(waveString);

            //Write out modified tree to scriptfile.
            ScriptParser parser = new ScriptParser(this.currentTreeModel);
            String scriptString = getCurrentScriptString();
            Path scriptPath = Paths.get(scriptString);
            parser.writeModelToFile(scriptPath.toString());

            //Update UI
            ((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent()).setUserObject(waveString);
            ((DefaultTreeModel) currentTree.getModel())
                    .nodeChanged((DefaultMutableTreeNode) currentTree.getLastSelectedPathComponent());
            JOptionPane.showMessageDialog(this, "Sound file successfully replaced.");

        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Unable to replace sound.\nDetails: " + ex.getMessage(),
                    "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}

From source file:com.clough.android.adbv.view.MainFrame.java

public MainFrame(IOManager ioManager, HistoryManager historyManager) {
    this();/*w w w  .  j  av  a  2  s.  c o m*/
    this.ioManager = ioManager;
    this.historyManager = historyManager;
    ioManager.addConnectionLostListener(new IOManager.ConnectionLostListener() {
        @Override
        public void onDisconnect() {
            showDeviceDisconnectedDialog();
        }
    });

    new SwingWorker<Void, Void>() {
        @Override
        protected Void doInBackground() throws Exception {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
            try {
                applicationID = MainFrame.this.ioManager.getApplicationID();
                deviceName = MainFrame.this.ioManager.getDeviceName();
                databaseName = MainFrame.this.ioManager.getDatabaseName();
                setTitle(ValueHolder.WINDOW_TITLE + " - (" + deviceName + " - " + applicationID + ")");
            } catch (IOManagerException ex) {
                showDeviceDisconnectedDialog();
            }
            return null;
        }

        @Override
        protected void done() {
            closeProgressDialog();
        }

    }.execute();
    showProgressDialog(true, 0, "Waiting for device/app info");

    refreshDatabase();

    tableInfoTree.setCellRenderer(new DefaultTreeCellRenderer() {

        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) value;
            String nodeString = String.valueOf(dmtn.getUserObject());
            ImageIcon selectedImageIcon = null;
            if (nodeString.equals(databaseName)) {
                selectedImageIcon = ValueHolder.Icons.DATABASE;
            } else {
                l: for (int i = 0; i < tables.length; i++) {
                    String tableName = tables[i];
                    if (tableName.equals(nodeString)) {
                        selectedImageIcon = ValueHolder.Icons.TABLE;
                        break;
                    } else if (i == tables.length - 1) {
                        for (int p = 0; p < tables.length; p++) {
                            for (int j = 0; j < columns[p].length; j++) {
                                String columnName = columns[p][j];
                                if (columnName.equals(nodeString)) {
                                    selectedImageIcon = ValueHolder.Icons.PENCIL;
                                    break l;
                                } else if (j == columns[p].length - 1) {
                                    for (int q = 0; q < tables.length; q++) {
                                        for (int r = 0; r < columns[q].length; r++) {
                                            for (int k = 0; k < columnInfos[q][r].length; k++) {
                                                String columnInfo = columnInfos[q][r][k];
                                                if (columnInfo.equals(nodeString)) {
                                                    switch (k) {
                                                    case 0: {
                                                        selectedImageIcon = ValueHolder.Icons.HASH_TAG;
                                                        break l;
                                                    }
                                                    case 1: {
                                                        selectedImageIcon = ValueHolder.Icons.BLUE;
                                                        break l;
                                                    }
                                                    case 2: {
                                                        selectedImageIcon = ValueHolder.Icons.ORANGE;
                                                        break l;
                                                    }
                                                    case 3: {
                                                        selectedImageIcon = ValueHolder.Icons.GREEN;
                                                        break l;
                                                    }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            setIcon(selectedImageIcon);
            return this;
        }

    });

    tableInfoTree.addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent evt) {
            Object[] data = evt.getPath().getPath();
            selectedTreeNodeValue = String.valueOf(data[data.length - 1]);
        }
    });

    tableInfoTree.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent evt) {
            if (evt.getButton() == MouseEvent.BUTTON3) {
                if (selectedTreeNodeValue.equals(databaseName)) {
                    showTreeNodePopup(evt.getX(), evt.getY(), true);
                } else {
                    for (String table : tables) {
                        if (table.equals(selectedTreeNodeValue)) {
                            showTreeNodePopup(evt.getX(), evt.getY(), false);
                            break;
                        }
                    }
                }
            } else if (evt.getClickCount() >= 2) {
                queryingTextArea.setText(queryingTextArea.getText() + "`" + selectedTreeNodeValue + "`");
            }
        }

    });

    currentHistoryList = historyManager.getHistoryList();
    for (int i = 0; i < currentHistoryList.size(); i++) {
        String[] history = currentHistoryList.get(i);
        historyContainingPanel.add(
                new HistoryItemPanel(i + 1, history[0].equals(applicationID), history[1], queryingTextArea));
    }
    adjustHistoryScrollbar();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MainFrame.this.historyManager.saveApplicationDb();
            } catch (HistoryManagerException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage(), "Application history saving",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }));

}

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

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("Rename ...")) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
        QueryMasterData ndata = (QueryMasterData) node.getUserObject();
        Object inputValue = JOptionPane.showInputDialog(this, "Rename this query to: ", "Rename Query Dialog",
                JOptionPane.PLAIN_MESSAGE, null, null,
                ndata.name().substring(0, ndata.name().lastIndexOf("[") - 1));

        if (inputValue != null) {
            String newQueryName = (String) inputValue;
            String requestXml = ndata.writeRenameQueryXML(newQueryName);
            lastRequestMessage = requestXml;

            setCursor(new Cursor(Cursor.WAIT_CURSOR));

            String response = QueryListNamesClient.sendQueryRequestREST(requestXml);
            if (response.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);
                    }/*from  w  ww .j a va2s  .  com*/
                });
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }
            lastResponseMessage = response;

            if (response != null) {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                try {
                    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                    StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                    String status = statusType.getType();

                    if (status.equalsIgnoreCase("DONE")) {
                        ndata.name(newQueryName + " [" + ndata.userId() + "]");
                        node.setUserObject(ndata);
                        //DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();

                        jTree1.repaint();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    } else if (e.getActionCommand().equalsIgnoreCase("Delete")) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
        QueryMasterData ndata = (QueryMasterData) node.getUserObject();
        Object selectedValue = JOptionPane.showConfirmDialog(this, "Delete Query \"" + ndata.name() + "\"?",
                "Delete Query Dialog", JOptionPane.YES_NO_OPTION);
        if (selectedValue.equals(JOptionPane.YES_OPTION)) {
            System.out.println("delete " + ndata.name());
            String requestXml = ndata.writeDeleteQueryXML();
            lastRequestMessage = requestXml;
            //System.out.println(requestXml);

            setCursor(new Cursor(Cursor.WAIT_CURSOR));

            String response = QueryListNamesClient.sendQueryRequestREST(requestXml);
            if (response.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);
                    }
                });
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }
            lastResponseMessage = response;

            if (response != null) {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                try {
                    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                    StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                    String status = statusType.getType();

                    if (status.equalsIgnoreCase("DONE")) {
                        treeModel.removeNodeFromParent(node);

                        //jTree1.repaint();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    } else if (e.getActionCommand().equalsIgnoreCase("Refresh All")) {
        String status = loadPreviousQueries(false);
        if (status.equalsIgnoreCase("")) {
            reset(200, false);
        } else if (status.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);
                }
            });
        }
    }
}

From source file:edu.ku.brc.specify.tasks.subpane.security.SecurityAdminPane.java

/**
 * //from   w  ww  . ja v  a  2 s  .co  m
 */
private void createNavigationTree() {
    TreeSelectionListener tsl = new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent tse) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();

            if (node == null || !(node.getUserObject() instanceof DataModelObjBaseWrapper)) {
                // Nothing is selected or object type isn't relevant
                clearPanels();
                return;
            }

            // ask if user he wants to discard changes if that's the case
            if (!aboutToShutdown()) {
                clearPanels();
                return;
            }

            DataModelObjBaseWrapper dataWrp = (DataModelObjBaseWrapper) (node.getUserObject());

            // get parent if it is a user
            /*DataModelObjBaseWrapper userObjWrp    = null;
            DataModelObjBaseWrapper groupObjWrp   = null;
            DataModelObjBaseWrapper collectionWrp = null;
            Object                  dataObj     = dataWrp.getDataObj();
            if (dataObj instanceof SpecifyUser)
            {
            // XXX Also might need to check to see if anyone is logged into the Group
            // when editing a Group
            SpecifyUser currentUser = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
            SpecifyUser spUser      = (SpecifyUser)dataObj;
                    
            if (!spUser.getIsLoggedIn() || currentUser.getId().equals(spUser.getId()))
            {
                DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
                userObjWrp    = (DataModelObjBaseWrapper) node.getUserObject();
                groupObjWrp   = (DataModelObjBaseWrapper) parent.getUserObject();
                collectionWrp = (DataModelObjBaseWrapper) ((DefaultMutableTreeNode)parent.getParent()).getUserObject();
                        
            } else
            {
                UIRegistry.showLocalizedError("SecuirytAdminPane.USR_IS_ON", spUser.getName());
                        
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run()
                    {
                        tree.clearSelection();
                    }
                });
                return;
            }
            }
                    
            nodesDiscipline = navTreeMgr.getParentOfClass(node, Discipline.class);
            nodesDivision   = nodesDiscipline != null ? nodesDiscipline.getDivision() : null;
            showInfoPanel(dataWrp, userObjWrp, groupObjWrp, collectionWrp, node.toString());
            updateUIEnabled(dataWrp);*/

            // get parent if it is a user
            DataModelObjBaseWrapper secondObjWrp = null;
            DataModelObjBaseWrapper collectionWrp = null;
            Object dataObj = dataWrp.getDataObj();
            if (dataObj instanceof SpecifyUser) {
                // XXX Also might need to check to see if anyone is logged into the Group
                // when editing a Group
                SpecifyUser currentUser = AppContextMgr.getInstance().getClassObject(SpecifyUser.class);
                SpecifyUser spUser = (SpecifyUser) dataObj;

                if (!spUser.getIsLoggedIn() || currentUser.getId().equals(spUser.getId())) {
                    DefaultMutableTreeNode parent = (DefaultMutableTreeNode) node.getParent();
                    secondObjWrp = (DataModelObjBaseWrapper) parent.getUserObject();
                    collectionWrp = (DataModelObjBaseWrapper) ((DefaultMutableTreeNode) parent.getParent())
                            .getUserObject();
                } else {
                    UIRegistry.showLocalizedError("SecuirytAdminPane.USR_IS_ON", spUser.getName());

                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            tree.clearSelection();
                        }
                    });
                    return;
                }
            }

            nodesDiscipline = navTreeMgr.getParentOfClass(node, Discipline.class);
            nodesDivision = nodesDiscipline != null ? nodesDiscipline.getDivision() : null;
            showInfoPanel(dataWrp, secondObjWrp, collectionWrp, node.toString());
            updateUIEnabled(dataWrp);
        }
    };

    DefaultTreeModel model = createNavigationTreeModel();
    tree = new JTree(model);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setRootVisible(false);
    tree.setCellRenderer(new MyTreeCellRenderer());
    tree.addTreeSelectionListener(tsl);

    // Expand the tree
    for (int i = 0; i < tree.getRowCount(); i++) {
        tree.expandRow(i);
    }

    for (int i = tree.getRowCount() - 1; i >= 1; i--) {
        if (tree.getPathForRow(i).getPathCount() > 3) {
            tree.collapseRow(i);
        }
    }

    navTreeMgr = new NavigationTreeMgr(tree, spUsers);

    // create object that will control the creation of popups
    // constructor will take care of hooking up right listeners to the tree.
    navTreeContextMgr = new NavigationTreeContextMenuMgr(navTreeMgr);

    IconManager.IconSize iconSize = IconManager.IconSize.Std20;
    ImageIcon sysIcon = IconManager.getIcon("SystemSetup", iconSize);
    JLabel label = createLabel("XXXX");

    label.setIcon(sysIcon);
    label.setBorder(BorderFactory.createEmptyBorder(1, 0, 0, 0));

    tree.setRowHeight(label.getPreferredSize().height);

    // Why doesn't this work?
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            tree.expandRow(1);
        }
    });

    //expandAll(tree, true);
}

From source file:net.sf.xmm.moviemanager.commands.importexport.IMDbInfoUpdater.java

@SuppressWarnings("unchecked")
public void execute() {

    /* Setting the priority of the thread to 4 to give the GUI room to update more often */
    Thread.currentThread().setPriority(4);

    DefaultMutableTreeNode root = (DefaultMutableTreeNode) ((DefaultTreeModel) MovieManager.getDialog()
            .getMoviesList().getModel()).getRoot();
    final Enumeration<DefaultMutableTreeNode> enumeration = root.children();

    lengthOfTask = root.getChildCount();

    try {//from  w ww  . ja  va 2s .co m

        Runnable threadRunner = new Runnable() {

            public void run() {

                DefaultMutableTreeNode node;
                ModelEntry model;

                ModelMovieInfo modelInfo = new ModelMovieInfo();
                IMDb imdb;
                try {
                    imdb = IMDbLib.newIMDb(MovieManager.getConfig().getHttpSettings());

                    while (enumeration.hasMoreElements()) {

                        if (canceled)
                            break;

                        // Will start only threadCount number of threads
                        while (threadHandler.getThreadCount() > threadCount - 1) {
                            threadHandler.waitForNextDecrease();
                        }

                        node = enumeration.nextElement();
                        model = (ModelEntry) node.getUserObject();

                        if (!model.getHasGeneralInfoData()) {
                            model.updateGeneralInfoData();
                        }

                        if (!model.getHasAdditionalInfoData()) {
                            model.updateAdditionalInfoData();
                        }

                        /* wrapping each movie in a thread */
                        Thread t = new Thread(new GetInfo(modelInfo, model, imdb));
                        t.start();

                        // Wait till the new thread has started and increased the thread count.
                        threadHandler.waitForNextIncrease();
                    }

                    do {
                        threadHandler.waitForNextDecrease();

                        if (threadHandler.getNoAction()) {
                            log.debug("No threads have finished within timeout of " + threadHandler.getTimeout()
                                    + "ms.");

                            ArrayList<GetInfo> active = threadHandler.getActiveThreads();

                            log.debug("Active threads:");

                            for (GetInfo t : active) {
                                log.debug(t.getTitle());
                            }
                        }

                    } while (threadHandler.getThreadCount() > 0);

                    setDone();

                    log.debug("Done updating list!");

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

        Thread t = new Thread(threadRunner);
        t.start();

    } catch (Exception e) {
        log.warn("Exception:" + e.getMessage());
    }
}