Java Code Examples for javax.swing.tree.DefaultTreeModel#getRoot()

The following examples show how to use javax.swing.tree.DefaultTreeModel#getRoot() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CatalogTree_simpleDifferentTests.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testThatGetComponentGetsAWellDefinedJTreeComponent() {
    Assume.assumeTrue(!GraphicsEnvironment.isHeadless());
    final CatalogTree catalogTree = new CatalogTree(null, new DefaultAppContext(""), null);
    final Component component = catalogTree.getComponent();

    assertNotNull(component);
    assertTrue(component instanceof JTree);
    final JTree tree = (JTree) component;
    assertEquals(false, tree.isRootVisible());
    assertNotNull(tree.getModel());
    assertEquals(true, tree.getModel() instanceof DefaultTreeModel);

    final DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
    assertNotNull(model.getRoot());
    assertEquals(true, model.getRoot() instanceof DefaultMutableTreeNode);
    final DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) model.getRoot();
    assertNotNull(rootNode.getUserObject());
    assertEquals(true, rootNode.getUserObject() instanceof String);
    assertEquals("root", rootNode.getUserObject().toString());
}
 
Example 2
Source File: MongoEditionPanel.java    From nosql4idea with Apache License 2.0 6 votes vote down vote up
public void addKey(String key, Object value) {

        List<TreeNode> node = new LinkedList<TreeNode>();
        NoSqlTreeNode treeNode = new NoSqlTreeNode(MongoKeyValueDescriptor.createDescriptor(key, value));

        if (value instanceof DBObject) {
            JsonTreeModel.processDbObject(treeNode, (DBObject) value);
        }

        node.add(treeNode);

        DefaultTreeModel treeModel = (DefaultTreeModel) editTableView.getTree().getModel();
        NoSqlTreeNode parentNode = getParentNode();
        if (parentNode == null) {
            parentNode = (NoSqlTreeNode) treeModel.getRoot();
        }
        TreeUtil.addChildrenTo(parentNode, node);
        treeModel.reload(parentNode);
    }
 
Example 3
Source File: TreeUtil.java    From Zettelkasten with GNU General Public License v3.0 6 votes vote down vote up
/**
 * This method selects the first entry in a jTree that start with the text
 * that is entered in the filter-textfield.
 *
 * @param tree the jTree where the item should be selected
 * @param textfield the related filtertextfield that contains the user-input
 */
public static void selectByTyping(javax.swing.JTree tree, javax.swing.JTextField textfield) {
    DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel();
    MutableTreeNode root = (MutableTreeNode) dtm.getRoot();
    String text = textfield.getText().toLowerCase();
    if (root != null && !text.isEmpty()) {
        for (int cnt = 0; cnt < dtm.getChildCount(root); cnt++) {
            MutableTreeNode child = (MutableTreeNode) dtm.getChild(root, cnt);
            String childtext = child.toString().toLowerCase();
            if (childtext.startsWith(text)) {
                TreePath tp = new TreePath(root);
                tp = tp.pathByAddingChild(child);
                tree.setSelectionPath(tp);
                tree.scrollPathToVisible(tp);
                return;
            }
        }
    }
}
 
Example 4
Source File: AquaLocationSourceList.java    From pumpernickel with MIT License 6 votes vote down vote up
public AquaLocationSourceList(LocationHistory directoryStack,
		GraphicCache graphicCache) {
	super(new DefaultTreeModel(new DefaultMutableTreeNode("root")));

	treeModel = (DefaultTreeModel) getModel();
	root = (DefaultMutableTreeNode) treeModel.getRoot();

	this.directoryStack = directoryStack;
	this.graphicCache = graphicCache;

	treeModel.insertNodeInto(devices, root, 0);
	treeModel.insertNodeInto(places, root, 1);
	addTreeSelectionListener(treeSelectionListener);
	directoryStack.addChangeListener(directoryStackListener);
	setExpandsSelectedPaths(true);
	setCellRenderer(new SourceListLocationRenderer(graphicCache, this));
	getSelectionModel().setSelectionMode(
			TreeSelectionModel.SINGLE_TREE_SELECTION);
	setUI(new SourceListTreeUI(this));

	expandPath(new TreePath(devices.getPath()));
	expandPath(new TreePath(places.getPath()));
}
 
Example 5
Source File: ComponentSelector.java    From Logisim with GNU General Public License v3.0 6 votes vote down vote up
public void setLogModel(Model value) {
	this.logModel = value;

	DefaultTreeModel model = (DefaultTreeModel) getModel();
	CircuitNode curRoot = (CircuitNode) model.getRoot();
	CircuitState state = logModel == null ? null : logModel.getCircuitState();
	if (state == null) {
		if (curRoot != null)
			model.setRoot(null);
		return;
	}
	if (curRoot == null || curRoot.circuitState != state) {
		curRoot = new CircuitNode(null, state, null);
		model.setRoot(curRoot);
	}
}
 
Example 6
Source File: EditorDeTipos.java    From brModelo with GNU General Public License v3.0 6 votes vote down vote up
public void SelecioneByDiagramaSelecionado() {
    DefaultTreeModel df = (DefaultTreeModel) tree.getModel();
    if (df.getRoot() instanceof TreeItem) {
        TreeItem root = (TreeItem) df.getRoot();
        TreePath pt = new TreePath(root);
        if (diagrama.getSelecionado() == null || !(diagrama.getSelecionado() instanceof Forma)) {
            return;
        }

        for (int i = 0; i < root.getChildCount(); i++) {
            TreeItem item = (TreeItem) root.getChildAt(i);
            if (item.getId() == diagrama.getSelecionado().getID()) {
                tree.setSelectionPath(pt.pathByAddingChild(item));
                break;
            }
        }
    }
    btnOK.setText("OK");
    btnFechar.setVisible(false);
}
 
Example 7
Source File: TreeModelEditor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns textual representation of the tree model.
 * 
 * @return textual representation of the tree model.
 */
String getCodeValue() {
    Object value = getValue();
    if (value instanceof DefaultTreeModel) {
        DefaultTreeModel model = (DefaultTreeModel)value;
        Object root = model.getRoot();
        if (root instanceof DefaultMutableTreeNode) {
            DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode)root;
            Object userObject = rootNode.getUserObject();
            if (userObject instanceof CodeUserObject) {
                CodeUserObject code = (CodeUserObject)userObject;
                return code.code;
            }
        }
    }
    return null;
}
 
Example 8
Source File: TreeModelEditor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns source code for the current value.
 * 
 * @return source code for the current value.
 */
@Override
public String getSourceCode() {
    DefaultTreeModel model = (DefaultTreeModel)getValue();
    
    // Nodes
    DefaultMutableTreeNode root = (DefaultMutableTreeNode)model.getRoot();
    StringBuilder buf = new StringBuilder();
    String rootVarName = generateCode(root, null, 0, buf);

    // The model itself
    RADProperty prop = (RADProperty)this.property;
    RADComponent comp = prop.getRADComponent();
    CodeVariable var = comp.getCodeExpression().getVariable();
    String varName = (var == null) ? null : var.getName();
    String setter = prop.getPropertyDescriptor().getWriteMethod().getName();
    if (varName != null) {
        setter = varName + '.' + setter;
    }
    buf.append(setter).append("(new "); // NOI18N
    buf.append(DefaultTreeModel.class.getName()).append('(').append(rootVarName).append("));\n"); // NOI18N

    return buf.toString();
}
 
Example 9
Source File: ViewManager.java    From leetcode-editor with Apache License 2.0 6 votes vote down vote up
public static void pick(JTree tree, JBScrollPane scrollPane) {

        DefaultTreeModel treeMode = (DefaultTreeModel) tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeMode.getRoot();
        if (root.isLeaf()) {
            return;
        }
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(0);
        if (node.isLeaf()) {
            return;
        }
        int i = (int) (Math.random() * node.getChildCount());
        DefaultMutableTreeNode select = (DefaultMutableTreeNode) node.getChildAt(i);

        TreePath toShowPath = new TreePath(select.getPath());
        tree.setSelectionPath(toShowPath);
        Rectangle bounds = tree.getPathBounds(toShowPath);
        Point point = new Point(0, (int) bounds.getY());
        JViewport viewport = scrollPane.getViewport();
        viewport.setViewPosition(point);
        return;
    }
 
Example 10
Source File: ProgramTreeActionManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
void setProgramTreeView(String treeName, ProgramDnDTree tree) {
	if (this.tree != null) {
		this.tree.removeTreeSelectionListener(selectionListener);
	}

	this.tree = tree;
	pasteMgr.setProgramTreeView(tree);

	if (tree != null) {
		DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();
		root = (ProgramNode) treeModel.getRoot();
		viewList = tree.getViewList();
		tree.addTreeSelectionListener(selectionListener);
	}
}
 
Example 11
Source File: ClasspathArchiveEntry.java    From ApkToolPlus with Apache License 2.0 5 votes vote down vote up
private void addEntry(String path, DefaultTreeModel model, boolean reset) {

        String[] pathComponents = path.replace('\\', '/').split("/");
        ClassTreeNode currentNode = (ClassTreeNode)model.getRoot();
        for (int i = 0; i < pathComponents.length; i++) {
            String pathComponent = pathComponents[i];
            currentNode = addOrFindNode(pathComponent, currentNode, i < pathComponents.length - 1, model, reset);
        }
    }
 
Example 12
Source File: QueryKBServerTask.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
private void updateMainPaneJTreeUI() {
    DefaultTreeModel model = (DefaultTreeModel) jTree.getModel();
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
    root.removeAllChildren();
    projectTree.updateRoot(root, projectNodes);
    model.reload(root);
    jTree.addTreeSelectionListener(projectTree.getTreeSelectionListener(root));
    ToolTipManager.sharedInstance().registerComponent(jTree);
    jTree.setCellRenderer(projectTree.getJTreeCellRenderer());
    jTree.addMouseListener(projectTree.getMouseListener(root));
    jTree.addKeyListener(projectTree.getKeyListener());
    windowObjects.getjTreeScrollPane().setViewportView(jTree);
}
 
Example 13
Source File: ScopeTreeViewPanel.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void reload(@Nullable final DefaultMutableTreeNode rootToReload) {
  final DefaultTreeModel treeModel = (DefaultTreeModel)myTree.getModel();
  if (rootToReload != null && rootToReload != treeModel.getRoot()) {
    final List<TreePath> treePaths = TreeUtil.collectExpandedPaths(myTree, new TreePath(rootToReload.getPath()));
    final List<TreePath> selectionPaths = TreeUtil.collectSelectedPaths(myTree, new TreePath(rootToReload.getPath()));
    final TreePath path = new TreePath(rootToReload.getPath());
    final boolean wasCollapsed = myTree.isCollapsed(path);
    final Runnable runnable = new Runnable() {
      @Override
      public void run() {
        if (!isTreeShowing() || rootToReload.getParent() == null) return;
        TreeUtil.sort(rootToReload, getNodeComparator());
        treeModel.reload(rootToReload);
        if (!wasCollapsed) {
          myTree.collapsePath(path);
          for (TreePath treePath : treePaths) {
            myTree.expandPath(treePath);
          }
          for (TreePath selectionPath : selectionPaths) {
            TreeUtil.selectPath(myTree, selectionPath);
          }
        }
      }
    };
    if (ApplicationManager.getApplication().isUnitTestMode()) {
      runnable.run();
    }
    else {
      SwingUtilities.invokeLater(runnable);
    }
  }
  else {
    TreeUtil.sort(treeModel, getNodeComparator());
    treeModel.reload();
  }
}
 
Example 14
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private static void allNodesChanged(JTree tree) {
  DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
  DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
  // Java 9: Collections.list(root.preorderEnumeration()).stream()
  Collections.list((Enumeration<?>) root.preorderEnumeration()).stream()
    .filter(TreeNode.class::isInstance).map(TreeNode.class::cast)
    .forEach(model::nodeChanged);
}
 
Example 15
Source File: ResourceExplorerTopComponent.java    From syncope with Apache License 2.0 5 votes vote down vote up
public ResourceExplorerTopComponent() {

        initComponents();
        setName(PluginConstants.ROOT_NAME);
        setToolTipText(PluginConstants.TOOL_TIP_TEXT);

        treeModel = (DefaultTreeModel) resourceExplorerTree.getModel();
        root = (DefaultMutableTreeNode) treeModel.getRoot();
        visibleRoot = new DefaultMutableTreeNode(PluginConstants.ROOT_NAME);
        mailTemplates = new DefaultMutableTreeNode(PluginConstants.MAIL_TEMPLATES);
        reportXslts = new DefaultMutableTreeNode(PluginConstants.REPORT_XSLTS);
        groovyScripts = new DefaultMutableTreeNode(PluginConstants.GROOVY_SCRIPTS);
        root.add(visibleRoot);
        initTemplatesTree();
    }
 
Example 16
Source File: FramePrincipal.java    From brModelo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void DoComandoExterno(Controler.menuComandos c) {
    if (c == Controler.menuComandos.cmdPrint) {
        fmImpressao fm = controladorImpressao;
        fm.rdMostarAI.setSelected(mostarAreaImpressao);
        fm.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        fm.setLocationRelativeTo(this);
        fm.setDiagrama(Manager.diagramaAtual);
        fm.setVisible(true);
        Point res = fm.getTamanhoAreaImpressao();
        mostarAreaImpressao = fm.rdMostarAI.isSelected();
        Manager.setMostrarAreaImpressao(mostarAreaImpressao, res.x, res.y);
    }
    if (c == menuComandos.cmdTreeNavegador) {
        TreeItensDiagrama.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        TreeItensDiagrama.setModel(new DefaultTreeModel(Manager.diagramaAtual.getTreeNavegacao()));
        if (formPartes != null && formPartes.isVisible()) {
            formPartes.Popule(Manager.diagramaAtual.getTipo());
        }
    }
    if ((TabInspector.getSelectedIndex() == 1) && (c == menuComandos.cmdTreeNavegador || c == menuComandos.cmdTreeSelect)) {
        DefaultTreeModel df = (DefaultTreeModel) TreeItensDiagrama.getModel();
        if (df.getRoot() instanceof TreeItem) {
            TreeItem root = (TreeItem) df.getRoot();
            TreePath pt = new TreePath(root);
            if (Manager.diagramaAtual.getSelecionado() == null || !(Manager.diagramaAtual.getSelecionado() instanceof Forma)) {
                noTree = true;
                TreeItensDiagrama.setSelectionPath(pt);
                noTree = false;
            } else {
                boolean done = false;
                int rp = Manager.diagramaAtual.getSelecionado().getID();
                for (int i = 0; i < root.getChildCount(); i++) {
                    TreeItem item = (TreeItem) root.getChildAt(i);
                    if (item.getId() == rp) {
                        if (TreeItensDiagrama.getLastSelectedPathComponent() != null) {
                            int v = ((TreeItem) TreeItensDiagrama.getLastSelectedPathComponent()).getId();
                            if (v != rp) {
                                noTree = true;
                                TreeItensDiagrama.setSelectionPath(pt.pathByAddingChild(item));
                                noTree = false;
                            }
                        } else {
                            noTree = true;
                            TreeItensDiagrama.setSelectionPath(pt.pathByAddingChild(item));
                            noTree = false;
                        }
                        done = true;
                        break;
                    }
                }
                if (!done) {
                    noTree = true;
                    TreeItensDiagrama.setSelectionPath(pt);
                    noTree = false;
                }
            }
        }
    }
}
 
Example 17
Source File: TemplatesUI.java    From CodeGen with MIT License 4 votes vote down vote up
@Override
public void apply() {
    List<CodeRoot> roots = new ArrayList<>();
    DefaultTreeModel treeModel = (DefaultTreeModel) templateTree.getModel();
    DefaultMutableTreeNode topNode = (DefaultMutableTreeNode) treeModel.getRoot();
    Enumeration rootEnum = topNode.children();
    // 获取所有root
    while (rootEnum.hasMoreElements()) {
        List<CodeGroup> groups = new ArrayList<>();
        DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) rootEnum.nextElement();
        Enumeration enumeration = rootNode.children();
        // 获取所有组
        while(enumeration.hasMoreElements()){
            List<CodeTemplate> templates = new ArrayList<>();
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement();
            Enumeration childEnum = node.children();
            // 获取所有模板
            while(childEnum.hasMoreElements()){
                DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) childEnum.nextElement();
                CodeTemplate template = (CodeTemplate) childNode.getUserObject();
                if(templateEditor != null){
                    CodeTemplate tmp = templateEditor.getCodeTemplate();
                    if(template.getId().equals(tmp.getId())){
                        template = tmp;
                    }
                }
                if (Objects.isNull(template.getOrder())) {
                    template.setOrder(Integer.valueOf(1));
                }
                templates.add(template);
            }
            CodeGroup group = (CodeGroup) node.getUserObject();
            Collections.sort(templates, Comparator.comparing(CodeTemplate::getOrder));
            group.setTemplates(templates);
            groups.add(group);
        }
        CodeRoot root = (CodeRoot) rootNode.getUserObject();
        root.setGroups(groups);
        roots.add(root);
    }
    settingManager.getTemplates().setRoots(roots);
    reset();
}
 
Example 18
Source File: ClassTree.java    From JByteMod-Beta with GNU General Public License v2.0 4 votes vote down vote up
public void refreshTree(JarArchive jar) {
  DefaultTreeModel tm = this.model;
  SortedTreeNode root = (SortedTreeNode) tm.getRoot();
  root.removeAllChildren();
  tm.reload();

  preloadMap = new HashMap<>();
  if (jar.getClasses() != null)
    for (ClassNode c : jar.getClasses().values()) {
      String name = c.name;
      String[] path = name.split("/");
      int i = 0;
      int slashIndex = 0;
      SortedTreeNode prev = root;
      while (true) {
        slashIndex = name.indexOf("/", slashIndex + 1);
        if (slashIndex == -1) {
          break;
        }
        String p = name.substring(0, slashIndex);
        if (preloadMap.containsKey(p)) {
          prev = preloadMap.get(p);
        } else {
          SortedTreeNode stn = new SortedTreeNode(path[i]);
          prev.add(stn);
          prev = stn;
          preloadMap.put(p, prev);
        }
        i++;
      }
      SortedTreeNode clazz = new SortedTreeNode(c);
      prev.add(clazz);
      for (MethodNode m : c.methods) {
        clazz.add(new SortedTreeNode(c, m));
      }
    }
  boolean sort = JByteMod.ops.get("sort_methods").getBoolean();
  sort(tm, root, sort);
  tm.reload();
  addListener();
  if (!expandedNodes.isEmpty()) {
    expandSaved(root);
  }
}
 
Example 19
Source File: WizardryScenarioDisk.java    From DiskBrowser with GNU General Public License v3.0 4 votes vote down vote up
public WizardryScenarioDisk (Disk disk)
// ---------------------------------------------------------------------------------//
{
  super (disk);

  if (false)
  {
    sectorTypesList.add (mazeSector);
    sectorTypesList.add (monsterSector);
    sectorTypesList.add (itemSector);
    sectorTypesList.add (characterSector);
    sectorTypesList.add (spellSector);
    sectorTypesList.add (messageSector);
    sectorTypesList.add (imageSector);
    sectorTypesList.add (experienceSector);
    sectorTypesList.add (treasureSector);
  }

  CodedMessage.codeOffset = 185;
  Monster.counter = 0;
  Item.counter = 0;

  DefaultTreeModel model = (DefaultTreeModel) catalogTree.getModel ();
  DefaultMutableTreeNode currentRoot = (DefaultMutableTreeNode) model.getRoot ();
  DefaultMutableTreeNode dataNode = findNode (currentRoot, "SCENARIO.DATA");
  DefaultMutableTreeNode msgNode = findNode (currentRoot, "SCENARIO.MESGS");
  if (dataNode == null || msgNode == null)
  {
    System.out.println ("Wizardry data or msg node not found");
    return;
  }
  dataNode.setAllowsChildren (true);
  msgNode.setAllowsChildren (true);

  scenarioHeader = new Header (dataNode, this);

  // Process SCENARIO.MESGS (requires scenario)
  AppleFileSource afs = (AppleFileSource) msgNode.getUserObject ();
  //    DefaultMutableTreeNode node = linkNode ("Messages", "Messages string", msgNode);
  extractMessages (msgNode, afs.getSectors ());
  //		makeNodeVisible (node);

  // Process SCENARIO.DATA (requires scenario and messages)
  afs = (AppleFileSource) dataNode.getUserObject ();
  List<DiskAddress> sectors = afs.getSectors ();

  extractItems (linkNode ("Items", "Items string", dataNode), sectors);
  extractRewards (linkNode ("Rewards", "Treasure string", dataNode), sectors);
  extractMonsters (linkNode ("Monsters", "Monsters string", dataNode), sectors);
  extractCharacters (linkNode ("Characters", "Characters string", dataNode), sectors);
  extractImages (linkNode ("Images", "Images string", dataNode), sectors);
  extractExperienceLevels (linkNode ("Experience", "Experience string", dataNode),
      sectors);
  //		node = linkNode ("Spells", "Spells string", dataNode);
  DefaultMutableTreeNode node = null;
  extractSpells (node, sectors);
  extractLevels (linkNode ("Maze", "Levels string", dataNode), sectors);
  // Make the Spells node (and its siblings) visible
  //		makeNodeVisible (node);

  // add information about each characters' baggage, spells known etc.
  for (Character c : characters)
  {
    c.linkItems (items);
    c.linkSpells (spells);
    int type = c.getStatistics ().typeInt;
    c.linkExperience (experiences.get (type));
  }
}
 
Example 20
Source File: FileGrabberDialog.java    From megabasterd with GNU General Public License v3.0 2 votes vote down vote up
private void _genFileList() {

        _files.clear();

        _total_space = 0L;

        DefaultTreeModel tree_model = (DefaultTreeModel) swingInvokeAndWaitForReturn((Callable) file_tree::getModel);

        DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree_model.getRoot();

        Enumeration files_tree = root.depthFirstEnumeration();

        while (files_tree.hasMoreElements()) {

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) files_tree.nextElement();

            if (node.isLeaf() && node != root) {

                String path = "";

                Object[] object_path = node.getUserObjectPath();

                for (Object p : object_path) {

                    path += File.separator + p;
                }

                path = path.replaceAll("^/+", "/").replaceAll("^\\+", "\\").trim().replaceAll(" \\[[0-9,.]+ [A-Z]+\\]$", "");

                File file = new File(path);

                if (file.isFile()) {

                    _total_space += file.length();

                    _files.add(file);
                }
            }
        }

        swingInvoke(() -> {
            total_file_size_label.setText("[" + formatBytes(_total_space) + "]");
        });

    }