Example usage for javax.swing.tree DefaultMutableTreeNode add

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

Introduction

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

Prototype

public void add(MutableTreeNode newChild) 

Source Link

Document

Removes newChild from its parent and makes it a child of this node by adding it to the end of this node's child array.

Usage

From source file:com.moss.bdbadmin.client.ui.BdbAdminClient.java

private void buildCategory(DefaultMutableTreeNode catNode, Category cat) {

    for (Category childCat : cat.categories()) {

        DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(childCat);
        catNode.add(childNode);

        buildCategory(childNode, childCat);
    }/*from w ww  . j a v  a  2 s  .  c om*/

    for (Env env : cat.environments()) {

        final DefaultMutableTreeNode envNode = new DefaultMutableTreeNode(env);
        catNode.add(envNode);

        Map<String, DefaultMutableTreeNode> primaryNameNodeMap = new HashMap<String, DefaultMutableTreeNode>();
        for (final Db db : env.databases()) {

            PrimaryDb primary = db.acceptVisitor(new DbVisitor<PrimaryDb>() {
                public PrimaryDb visit(PrimaryDb primary) {
                    return primary;
                }

                public PrimaryDb visit(SecondaryDb secondary) {
                    return null;
                }
            });

            if (primary != null) {
                DefaultMutableTreeNode primaryNode = new DefaultMutableTreeNode(primary);
                envNode.add(primaryNode);
                primaryNameNodeMap.put(primary.getName(), primaryNode);
            }
        }

        for (final Db db : env.databases()) {

            SecondaryDb secondary = db.acceptVisitor(new DbVisitor<SecondaryDb>() {
                public SecondaryDb visit(PrimaryDb primary) {
                    return null;
                }

                public SecondaryDb visit(SecondaryDb secondary) {
                    return secondary;
                }
            });

            if (secondary != null) {
                DefaultMutableTreeNode secondaryNode = new DefaultMutableTreeNode(secondary);
                DefaultMutableTreeNode primaryNode = primaryNameNodeMap.get(secondary.getPrimaryName());
                primaryNode.add(secondaryNode);
            }
        }
    }
}

From source file:edu.ucla.stat.SOCR.chart.ChartTree.java

private MutableTreeNode createItemLabelsNode() {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Item Labels");

    DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(
            new DemoDescription("edu.ucla.stat.SOCR.chart.demo.ItemLabelDemo1", "ItemLabelDemo1"));
    DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(
            new DemoDescription("edu.ucla.stat.SOCR.chart.demo.ItemLabelDemo2", "ItemLabelDemo2"));
    DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(
            new DemoDescription("edu.ucla.stat.SOCR.chart.demo.ItemLabelDemo3", "ItemLabelDemo3"));

    root.add(n1);
    root.add(n2);//from   w ww.  j  av a 2s  .  c o m
    root.add(n3);

    return root;
}

From source file:com.edduarte.protbox.core.registry.PReg.java

private boolean build(final DefaultMutableTreeNode treeRoot, final PbxFolder root) {
    root.getSubFolders().forEach(f -> {
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(f, true);
        newNode.setAllowsChildren(true);
        build(newNode, f);/*  w w  w . jav a2 s  .co  m*/
        treeRoot.add(newNode);
    });

    root.getSubFiles().forEach(f -> {
        DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(f, true);
        newNode.setAllowsChildren(false);
        treeRoot.add(newNode);
    });

    return false;
}

From source file:de.tor.tribes.ui.windows.DSWorkbenchSplashScreen.java

protected HIDE_RESULT hideSplash() {
    try {/*  w w w. j a  v a 2 s.co m*/
        if (!new File(".").canWrite()) {
            try {
                throw new IOException(
                        "Failed to access installation directory " + new File(".").getAbsolutePath());
            } catch (Exception e) {
                showFatalError(e);
                return HIDE_RESULT.ERROR;
            }
        }
        File f = new File("./servers");
        if (!f.exists() && !f.mkdir()) {
            try {
                throw new IOException(
                        "Failed to create server directory at location " + new File(".").getAbsolutePath());
            } catch (Exception e) {
                showFatalError(e);
                return HIDE_RESULT.ERROR;
            }
        }

        ProfileManager.getSingleton().loadProfiles();
        if (ProfileManager.getSingleton().getProfiles().length == 0) {
            logger.debug("Starting first start wizard");

            //first start wizard
            if (!new File("./hfsw").exists()) {
                logger.debug(" - Initializing first start wizard");
                Map result = new HashMap<>();

                try {
                    WizardPanelProvider provider = new FirstStartWizard();
                    Wizard wizard = provider.createWizard();
                    logger.debug(" - Showing wizard");
                    result = (Map) WizardDisplayer.showWizard(wizard);
                    logger.debug("Wizard finished with result " + result);
                } catch (Throwable t) {
                    logger.error("Wizard exception", t);
                    result = null;
                }
                logger.debug(" - Wizard has finished");
                if (result == null) {
                    logger.warn(" - Wizard returned no result. Startup will fail.");
                    JOptionPaneHelper.showWarningBox(self,
                            "Du musst die grundlegenden Einstellungen zumindest einmalig durchfhren,\n"
                                    + "um DS Workbench verwenden zu knnen. Bitte starte DS Workbench neu.",
                            "Abbruch");
                    return HIDE_RESULT.ERROR;
                } else {
                    logger.debug("Wizard result: " + result);
                }
                logger.debug("- First start wizard finished");
                GlobalOptions.addProperty("proxySet", result.get("proxySet").toString());
                GlobalOptions.addProperty("proxyHost", result.get("proxyHost").toString());
                GlobalOptions.addProperty("proxyPort", result.get("proxyPort").toString());
                GlobalOptions.addProperty("proxyType", result.get("proxyType").toString());
                GlobalOptions.addProperty("proxyUser", result.get("proxyUser").toString());
                GlobalOptions.addProperty("proxyPassword", result.get("proxyPassword").toString());
                GlobalOptions.addProperty("default.server", result.get("server").toString());
                GlobalOptions.addProperty("default.player", result.get("tribe.id").toString());
                logger.debug("Creating initial profile");
                UserProfile p = UserProfile.create(GlobalOptions.getProperty("default.server"),
                        result.get("tribe.name").toString());
                GlobalOptions.setSelectedProfile(p);
                GlobalOptions.addProperty("selected.profile", Long.toString(p.getProfileId()));
                logger.debug(" - Disabling first start wizard");
                FileUtils.touch(new File("./hfsw"));
                GlobalOptions.saveProperties();
            }
        }

        //load properties, cursors, skins, world decoration
        logger.debug("Adding startup listeners");
        DataHolder.getSingleton().addDataHolderListener(this);
        DataHolder.getSingleton().addDataHolderListener(DSWorkbenchSettingsDialog.getSingleton());
        GlobalOptions.addDataHolderListener(this);
    } catch (Exception e) {
        logger.error("Failed to initialize global options", e);
        showFatalError(e);
        return HIDE_RESULT.ERROR;
    }

    logger.debug("Starting profile selection");
    boolean settingsRestored = false;

    ServerManager.loadServerList(DSWorkbenchSettingsDialog.getSingleton().getWebProxy());
    try {
        //open profile selection
        if (ProfileManager.getSingleton().getProfiles().length == 0) {
            logger.debug("No profile exists, SettingsDialog will handle this");
            //no profile found...this is handles by the settings validation
        } else if (ProfileManager.getSingleton().getProfiles().length == 1) {
            logger.debug("One profile exists. Using it...");
            //only one single profile was found, use it
            UserProfile profile = ProfileManager.getSingleton().getProfiles()[0];
            String server = profile.getServerId();
            GlobalOptions.setSelectedServer(server);
            GlobalOptions.setSelectedProfile(profile);
            GlobalOptions.addProperty("default.server", server);
            GlobalOptions.addProperty("selected.profile", Long.toString(profile.getProfileId()));
        } else {
            logger.debug("More than one profiles exist. Showing selection dialog");
            File f = new File("./servers");
            List<String> servers = new LinkedList<>();
            for (File server : f.listFiles()) {
                servers.add(server.getName());
            }
            //sort server names
            Collections.sort(servers, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    if (o1.length() < o2.length()) {
                        return -1;
                    } else if (o1.length() > o2.length()) {
                        return 1;
                    }
                    return o1.compareTo(o2);
                }
            });
            List<Object> path = new LinkedList<>();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Profile");
            long selectedProfile = GlobalOptions.getProperties().getLong("selected.profile");
            path.add(root);
            for (String server : servers) {
                DefaultMutableTreeNode serverNode = new DefaultMutableTreeNode(server);
                boolean profileAdded = false;
                for (UserProfile profile : ProfileManager.getSingleton().getProfiles(server)) {
                    DefaultMutableTreeNode profileNode = new DefaultMutableTreeNode(profile);
                    if (profile.getProfileId() == selectedProfile) {
                        path.add(serverNode);
                        path.add(profileNode);
                    }
                    serverNode.add(profileNode);
                    profileAdded = true;
                }
                if (profileAdded) {
                    root.add(serverNode);
                }
            }

            jTree1.setModel(new DefaultTreeModel(root));
            jTree1.setSelectionPath(new TreePath(path.toArray()));
            jTree1.scrollPathToVisible(new TreePath(path.toArray()));
            jTree1.setCellRenderer(new ProfileTreeNodeRenderer());
            jProfileDialog.setVisible(true);
        }
        logger.debug("Profile selection finished");
        //check settings
        DSWorkbenchSettingsDialog.getSingleton().restoreProperties();
        settingsRestored = true;
        if (!DSWorkbenchSettingsDialog.getSingleton().checkSettings()) {
            logger.debug("Settings check in settings dialog failed");
            logger.info("Reading user settings returned error(s)");
            DSWorkbenchSettingsDialog.getSingleton().setBlocking(true);
            DSWorkbenchSettingsDialog.getSingleton().setVisible(true);
        }
    } catch (Exception e) {
        logger.warn("Failed to open profile manager", e);
    }

    if (!settingsRestored) {
        DSWorkbenchSettingsDialog.getSingleton().restoreProperties();
    }

    // <editor-fold defaultstate="collapsed" desc=" Check for data updates ">
    logger.debug("Checking for application updates");
    boolean checkForUpdates = GlobalOptions.getProperties().getBoolean("check.updates.on.startup");

    try {
        if (!DataHolder.getSingleton().loadData(checkForUpdates)) {
            throw new Exception("loadData() returned 'false'. See log for more details.");
        }
    } catch (Exception e) {
        logger.error("Failed to load server data", e);
        showFatalError(e);
        return HIDE_RESULT.ERROR;
    }
    // </editor-fold>
    try {
        logger.debug("Initializing application window");
        DSWorkbenchMainFrame.getSingleton().init();
        logger.info("Showing application window");

        DSWorkbenchMainFrame.getSingleton().setVisible(true);

        //check for version updates
        logger.info("Checking for DS Workbench update.");
        UpdateInfo info = GithubVersionCheck.getUpdateInformation();
        switch (info.getStatus()) {
        case UPDATE_AVAILABLE:
            NotifierFrame.doNotification(
                    "Eine neue DS Workbench Version ist verfgbar. Klick den grnen Punkt oben links, um auf die Download Seite zu gelangen. ",
                    NotifierFrame.NOTIFY_UPDATE);
        default:
            logger.info("No update available or update check failed.");
        }

        try {
            ReportServer.getSingleton().start(GlobalOptions.getProperties().getInt("report.server.port"));
        } catch (Exception e) {
            logger.error("Failed to start report server", e);
        }

        // <editor-fold defaultstate="collapsed" desc=" Init HelpSystem ">
        if (!Constants.DEBUG) {
            GlobalOptions.getHelpBroker().enableHelpKey(DSWorkbenchSimulatorFrame.getSingleton().getRootPane(),
                    "pages.astar", GlobalOptions.getHelpBroker().getHelpSet());
            GlobalOptions.getHelpBroker().enableHelpKey(DSWorkbenchMainFrame.getSingleton().getRootPane(),
                    "index", GlobalOptions.getHelpBroker().getHelpSet());
        }
        // </editor-fold>

        // <editor-fold defaultstate="collapsed" desc=" Init A*Star Servers ">
        ServerManager.giveSimulatorServerList();
        // </editor-fold>

        t.stopRunning();
        setVisible(false);
        GlobalOptions.removeDataHolderListener(this);

        return HIDE_RESULT.SUCCESS;
    } catch (Throwable th) {
        logger.fatal("Fatal error while running DS Workbench", th);
        showFatalError(th);
        return HIDE_RESULT.ERROR;
    }
}

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

protected void diffDumps(String prefix, DefaultMutableTreeNode root, Map dumpStore, TreePath[] dumps,
        int minOccurence, String regex) {
    List<String> keys = new Vector<>(dumps.length);

    for (final TreePath dump : dumps) {
        String dumpName = getDumpStringFromTreePath(dump);
        if (dumpName.indexOf(" at") > 0) {
            dumpName = dumpName.substring(0, dumpName.indexOf(" at"));
        } else if (dumpName.indexOf(" around") > 0) {
            dumpName = dumpName.substring(0, dumpName.indexOf(" around"));
        }// ww  w. j a  va  2 s .  com
        keys.add(dumpName);
    }

    String info = prefix + " between " + keys.get(0) + " and " + keys.get(keys.size() - 1);
    DefaultMutableTreeNode catMerge = new DefaultMutableTreeNode(
            new TableCategory(info, IconFactory.DIFF_DUMPS));
    root.add(catMerge);
    int threadCount = 0;

    if (dumpStore.get(keys.get(0)) != null) {

        for (final Object o : ((Map) dumpStore.get(keys.get(0))).keySet()) {
            String threadKey = ((String) o).trim();

            if (Strings.isNullOrEmpty(regex) || threadKey.matches(regex)) {
                int occurence = 0;
                for (int i = 1; i < dumps.length; i++) {
                    Map threads = (Map) dumpStore.get(keys.get(i));
                    if (threads.containsKey(threadKey)) {
                        occurence++;
                    }
                }

                if (occurence >= (minOccurence - 1)) {
                    threadCount++;
                    StringBuilder content = new StringBuilder("<body bgcolor=\"ffffff\"><b><font size=")
                            .append(TDA.getFontSizeModifier(-1)).append('>').append(keys.get(0))
                            .append("</b></font><hr><pre><font size=").append(TDA.getFontSizeModifier(-1))
                            .append('>').append(fixMonitorLinks(
                                    (String) ((Map) dumpStore.get(keys.get(0))).get(threadKey), keys.get(0)));

                    int maxLines = 0;
                    for (int i = 1; i < dumps.length; i++) {
                        if (((Map) dumpStore.get(keys.get(i))).containsKey(threadKey)) {
                            content.append("\n\n</pre><b><font size=");
                            content.append(TDA.getFontSizeModifier(-1));
                            content.append('>');
                            content.append(keys.get(i));
                            content.append("</font></b><hr><pre><font size=");
                            content.append(TDA.getFontSizeModifier(-1));
                            content.append('>');
                            content.append(fixMonitorLinks(
                                    (String) ((Map) dumpStore.get(keys.get(i))).get(threadKey), keys.get(i)));
                            int countLines = countLines(
                                    ((String) ((Map) dumpStore.get(keys.get(i))).get(threadKey)));
                            maxLines = maxLines > countLines ? maxLines : countLines;
                        }
                    }
                    addToCategory(catMerge, threadKey, null, content.toString(), maxLines, true);
                }
            }
        }
    }

    ((Category) catMerge.getUserObject()).setInfo(getStatInfo(keys, prefix, minOccurence, threadCount));

}

From source file:org.jfree.chart.demo.SuperDemo.java

private MutableTreeNode createLegendNode() {
    DefaultMutableTreeNode defaultmutabletreenode = new DefaultMutableTreeNode("Legends");
    DefaultMutableTreeNode defaultmutabletreenode1 = new DefaultMutableTreeNode(
            new DemoDescription("LegendWrapperDemo1", "LegendWrapperDemo1.java"));
    defaultmutabletreenode.add(defaultmutabletreenode1);
    return defaultmutabletreenode;
}

From source file:com.ibm.soatf.gui.SOATestingFrameworkGUI.java

/**
 * //from www.j a v  a2s .  c o  m
 * @param iface 
 */
private void updateDetails(GUIObjects.Interface iface) {
    final Interface ifaceMasterXML = iface.getWrappedObject();
    String name = ifaceMasterXML.getName();
    final InterfaceConfiguration ICFG;
    try {
        ICFG = MCFG.getInterfaceConfig(name);
    } catch (MasterConfigurationException ex) {
        logger.error("Can't load interface details.", ex);
        resetInterfaceDetails();
        return;
    }
    DefaultMutableTreeNode nodeInterface = new DefaultMutableTreeNode(iface);
    DefaultMutableTreeNode nodeProjects = new DefaultMutableTreeNode("SOA Projects");
    //Loop through all project defined in 
    //SOATestingFrameworkMasterConfiguration.Interfaces.Interface
    for (Project project : ifaceMasterXML.getProjects().getProject()) {
        DefaultMutableTreeNode nodeProject = new DefaultMutableTreeNode(new GUIObjects.Project(project));
        nodeProjects.add(nodeProject);
    }
    nodeInterface.add(nodeProjects);
    DefaultMutableTreeNode nodePatterns = new DefaultMutableTreeNode("Flow Patterns");
    /*for (Interface.Patterns.ReferencedFlowPattern refPattern : ifaceMasterXML.getPatterns().getReferencedFlowPattern()) {
     for (int i = 0; i < refPattern.getOccurrence(); i++) {
     String flowPatternId = refPattern.getIdentificator();
     FlowPattern flowPattern = MCFG.getFlowPattern(flowPatternId);
     DefaultMutableTreeNode nodeFlowPattern = new DefaultMutableTreeNode(new GUIObjects.FlowPattern(flowPattern));
     ICFG.getInterfaceFlowPattern(flowPatternId);
     for (TestScenario testScenario : flowPattern.getTestScenario()) {
     DefaultMutableTreeNode nodeTestScenario = new DefaultMutableTreeNode(new GUIObjects.TestScenario(testScenario));
     for (ExecutionBlock executionBlock : testScenario.getExecutionBlock()) {
     DefaultMutableTreeNode nodeExecutionBlock = new DefaultMutableTreeNode(new GUIObjects.ExecutionBlock(executionBlock));
     for (Operation operation : executionBlock.getOperation()) {
     DefaultMutableTreeNode nodeOperation = new DefaultMutableTreeNode(new GUIObjects.Operation(operation));
     nodeExecutionBlock.add(nodeOperation);
     }
     nodeTestScenario.add(nodeExecutionBlock);
     }
     nodeFlowPattern.add(nodeTestScenario);
     }
     nodePatterns.add(nodeFlowPattern);
     }
     }*/
    List<IfaceFlowPattern> ifaceFlowPatterns;
    try {
        ifaceFlowPatterns = ICFG.getIfaceFlowPatterns();
    } catch (InterfaceConfigurationException ex) {
        logger.error("Can't load interface flow patterns.", ex);
        resetInterfaceDetails();
        return;
    }
    for (IfaceFlowPattern iFlowPattern : ifaceFlowPatterns) {
        DefaultMutableTreeNode nodeInterfaceFlowPattern = new DefaultMutableTreeNode(
                new GUIObjects.IfaceFlowPattern(iFlowPattern));
        for (IfaceTestScenario iTestScenario : iFlowPattern.getIfaceTestScenario()) {
            DefaultMutableTreeNode nodeInterfaceTestScenario = new DefaultMutableTreeNode(
                    new GUIObjects.InterfaceTestScenario(iTestScenario));
            for (IfaceExecBlock iExecutionBlock : iTestScenario.getIfaceExecBlock()) {
                DefaultMutableTreeNode nodeInterfaceExecutionBlock = new DefaultMutableTreeNode(
                        new GUIObjects.InterfaceExecutionBlock(iExecutionBlock));
                ExecutionBlock executionBlock;
                try {
                    executionBlock = MCFG.getExecutionBlock(iFlowPattern.getRefId(), iTestScenario.getRefId(),
                            iExecutionBlock.getRefId());
                } catch (MasterConfigurationException ex) {
                    logger.error("Can't load execution block", ex);
                    resetInterfaceDetails();
                    return;
                }
                for (Operation operation : executionBlock.getOperation()) {
                    DefaultMutableTreeNode nodeOperation = new DefaultMutableTreeNode(
                            new GUIObjects.Operation(operation));
                    nodeInterfaceExecutionBlock.add(nodeOperation);
                }
                nodeInterfaceTestScenario.add(nodeInterfaceExecutionBlock);
            }
            TestScenarioPreOrPostExecutionBlock postExecBlock = null;
            try {
                postExecBlock = MCFG.getPostExecutionBlock(iFlowPattern.getRefId(), iTestScenario.getRefId());
            } catch (MasterConfigurationException ex) {
                ;
            }
            if (postExecBlock != null) {
                //TODO KROKY
            }
            nodeInterfaceFlowPattern.add(nodeInterfaceTestScenario);
        }
        nodePatterns.add(nodeInterfaceFlowPattern);
    }
    nodeInterface.add(nodePatterns);

    DefaultTreeModel defaultTreeModel = new DefaultTreeModel(nodeInterface);
    jtInterfaceDetails.setModel(defaultTreeModel);
}

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

/**
 * Assemble the list of nodes into a tree, based on the directory structure.
 */// ww  w. j a va  2  s . c o  m
public DefaultMutableTreeNode getTree(File basedir, List<DefaultMutableTreeNode> nodes, String pomFile) {
    Map<String, DefaultMutableTreeNode> map = getMap(nodes);
    for (DefaultMutableTreeNode child : nodes) {
        Project project = (Project) child.getUserObject();
        File pom = project.getPom();
        File pomDir = pom.getParentFile();
        File parentPom = new File(pomDir.getParentFile(), pomFile);
        String parentPomPath = parentPom.getAbsolutePath();
        DefaultMutableTreeNode parent = map.get(parentPomPath);
        if (parent != null) {
            parent.add(child);
        }
    }
    String rootPom = basedir + File.separator + pomFile;
    DefaultMutableTreeNode root = map.get(rootPom);

    return root;
}

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

/**
 * Create the context.//  w ww .  ja  v  a  2s  . co  m
 * @param console the main console.
 * @param locator$ the locator.
 * @return the digest display.
 */
@Override
public JContext instantiate(JMainConsole console, String locator$) {
    try {
        this.console = console;
        this.locator$ = locator$;
        Properties locator = Locator.toProperties(locator$);
        entihome$ = locator.getProperty(Entigrator.ENTIHOME);
        entityKey$ = locator.getProperty(EntityHandler.ENTITY_KEY);
        entityLabel$ = locator.getProperty(EntityHandler.ENTITY_LABEL);
        String compressedSelection$ = locator.getProperty(SELECTION);
        if (compressedSelection$ != null) {
            try {
                byte[] ba = Base64.decodeBase64(compressedSelection$);
                selection$ = new String(ba, "UTF-8");
            } catch (Exception ee) {
                Logger.getLogger(getClass().getName()).info(ee.toString());
            }
        }
        Entigrator entigrator = console.getEntigrator(entihome$);
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(entityLabel$);
        locator = new Properties();
        locator.setProperty(Locator.LOCATOR_TITLE, DIGEST);
        String icon$ = Support.readHandlerIcon(null, getClass(), "digest.png");
        locator.setProperty(Locator.LOCATOR_ICON, icon$);
        locator.setProperty(NODE_TYPE, NODE_TYPE_ROOT);
        root.setUserObject(Locator.toString(locator));
        DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode(entityLabel$);
        root.add(parentNode);
        Sack parent = entigrator.getEntityAtKey(entityKey$);
        String parentLocator$ = EntityHandler.getEntityLocator(entigrator, parent);
        parentLocator$ = Locator.append(parentLocator$, NODE_TYPE, NODE_TYPE_PARENT);
        parentNode.setUserObject(parentLocator$);
        tree = new JTree(root);
        tree.addTreeSelectionListener(new SelectionListener());
        tree.setShowsRootHandles(true);
        tree.setCellRenderer(new NodeRenderer());
        tree.addMouseListener(new MousePopupListener());
        scrollPane.getViewport().add(tree);
        facets = listFacetOpenItems();
        DefaultMutableTreeNode[] na = getFacetOpenItems();
        if (na != null)
            for (DefaultMutableTreeNode n : na)
                parentNode.add(n);
        expandTree(tree, true);
        select();
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).severe(e.toString());
    }
    return this;
}

From source file:base.BasePlayer.AddGenome.java

static void checkGenomes() {

    //DefaultMutableTreeNode
    File checkdir = Main.genomeDir, checkAnnodir;
    File[] addDir, annodir;/*from   ww w  .  ja  va  2  s.co m*/
    root.removeAllChildren();
    int counter = 0;
    for (int i = model.getRowCount() - 1; i >= 0; i--) {
        model.removeRow(i);
    }
    for (int i = remmodel.getRowCount() - 1; i >= 0; i--) {
        remmodel.removeRow(i);
    }

    removables.clear();

    int currentlen = 0, length = 0;
    if (checkdir == null) {
        try {
            checkdir = new File(userDir + "/genomes");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    addDir = checkdir.listFiles();
    for (int f = 0; f < addDir.length; f++) {

        try {
            if (!addDir[f].isDirectory()) {
                continue;
            }
            currentlen = genometable.getFontMetrics(genometable.getFont()).stringWidth(addDir[f].getName());
            if (currentlen > length) {
                length = currentlen;
            }

            AddGenome.removables.add(addDir[f].getName());
            checkAnnodir = new File(checkdir + "/" + addDir[f].getName() + "/annotation/");
            annodir = checkAnnodir.listFiles();
            DefaultMutableTreeNode genome = new DefaultMutableTreeNode(addDir[f].getName());
            root.add(genome);
            if (annodir == null) {
                counter++;
                genome.add(new DefaultMutableTreeNode("Add new annotation..."));
            } else {
                counter += annodir.length + 3;
                for (int a = 0; a < annodir.length; a++) {
                    currentlen = genometable.getFontMetrics(genometable.getFont())
                            .stringWidth(annodir[a].getName());
                    if (currentlen > length) {
                        length = currentlen;
                    }
                    genome.add(new DefaultMutableTreeNode(annodir[a].getName()));
                }
                genome.add(new DefaultMutableTreeNode("Add new annotation..."));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    if (counter == 0) {
        counter = 1;
        length = genometable.getFontMetrics(genometable.getFont()).stringWidth("Add new annotation...");
    }
    counter++;
    root.add(new DefaultMutableTreeNode("Add new reference..."));
    genometable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
    for (int i = 0; i < organisms.size(); i++) {
        if (!AddGenome.removables.contains(organisms.get(i))) {
            Object[] row = { organisms.get(i), "" + sizeHash.get(organisms.get(i))[0] / 1048576 };
            model.addRow(row);
            currentlen = genometable.getFontMetrics(genometable.getFont()).stringWidth(organisms.get(i));
            if (currentlen > length) {
                length = currentlen;
            }
        }
    }

    AddGenome.longestName = length;

    if (genometable.getRowCount() > 15) {
        genometable.setPreferredScrollableViewportSize((new Dimension(
                AddGenome.longestName + 20 + Main.defaultFontSize * 8, genometable.getRowHeight() * 15)));
        genometable.setMinimumSize(new Dimension(AddGenome.longestName + 20, genometable.getRowHeight() * 15));
    } else {
        genometable.setPreferredScrollableViewportSize(
                (new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8,
                        genometable.getRowHeight() * (genometable.getRowCount() + 1))));
        genometable.setMinimumSize(new Dimension(AddGenome.longestName + 20,
                genometable.getRowHeight() * (genometable.getRowCount() + 1)));
    }

    if (remtable.getRowCount() > 15) {
        remtable.setPreferredScrollableViewportSize((new Dimension(
                AddGenome.longestName + 20 + Main.defaultFontSize * 8, remtable.getRowHeight() * 15)));
    } else {
        remtable.setPreferredScrollableViewportSize(
                (new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8,
                        remtable.getRowHeight() * (remtable.getRowCount() + 1))));
    }
    //Main.defaultFontSize = 12;
    genometable.getColumnModel().getColumn(0).setPreferredWidth(AddGenome.longestName + 10);
    genometable.getColumnModel().getColumn(0).setMinWidth(AddGenome.longestName + 10);
    //   genometable.getColumnModel().getColumn(1).setPreferredWidth(Main.defaultFontSize*8);
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    model.reload();
    int rowheight = tree.getRowHeight();
    if (rowheight < 1) {
        rowheight = Main.defaultFontSize + 4;
    }

    treescroll.setPreferredSize(
            new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8, counter * rowheight));
    treescroll.setMinimumSize(
            new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8, counter * rowheight));
    remscroll.setPreferredSize(
            new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8, counter * rowheight));
    remscroll.setMinimumSize(
            new Dimension(AddGenome.longestName + 20 + Main.defaultFontSize * 8, counter * rowheight));
    tree.expandPath(new TreePath(root));

    setFonts(Main.menuFont);
}