javax.swing.JTree Java Examples

The following examples show how to use javax.swing.JTree. 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: MainFrameTree.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@SwingThread
void expandToFirstLeaf(int max) {
    Debug.println("expand to first leaf");
    if (leavesShown()) {
        return;
    }
    JTree jTree = getTree();
    int i = 0;
    while (true) {
        int rows = jTree.getRowCount();
        if (i >= rows || rows >= max) {
            break;
        }
        TreePath treePath = jTree.getPathForRow(i);
        Object lastPathComponent = treePath.getLastPathComponent();
        if (lastPathComponent instanceof BugLeafNode) {
            return;
        }
        jTree.expandRow(i++);
    }
}
 
Example #2
Source File: CProjectLoader.java    From binnavi with Apache License 2.0 6 votes vote down vote up
/**
 * Loads a project inside a thread.
 * 
 * @param parent Parent window used for dialogs.
 * @param project Project to load.
 * @param projectTree Project tree to expand on project loading. This argument can be null.
 */
private static void loadProjectThreaded(final Window parent, final INaviProject project,
    final JTree projectTree) {
  Preconditions.checkNotNull(parent, "IE00005: Parent argument can not be null");

  Preconditions.checkNotNull(project, "IE01284: Project argument can not be null");

  if (project.isLoading()) {
    return;
  }

  new Thread() {
    @Override
    public void run() {
      loadProjectInternal(parent, project, projectTree);
    }
  }.start();
}
 
Example #3
Source File: JTreeJavaElement.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
private boolean setCellSelection(Properties[] properties) {
    JTree tree = (JTree) component;
    if (properties.length == 0) {
        tree.setSelectionRows(new int[0]);
        return true;
    }
    List<TreePath> paths = new ArrayList<TreePath>();
    for (Properties propertie : properties) {
        TreePath path = getPath(tree, propertie.getProperty("Path"));
        if (path != null) {
            paths.add(path);
        }
    }
    if (paths.size() != properties.length) {
        return false;
    }
    tree.setSelectionPaths(paths.toArray(new TreePath[paths.size()]));
    return true;
}
 
Example #4
Source File: ProjectExplorer.java    From Logisim with GNU General Public License v3.0 6 votes vote down vote up
@Override
public boolean canPerformAction(JTree targetTree, Object draggedNode, int action, Point location) {
	TreePath pathTarget = targetTree.getPathForLocation(location.x, location.y);
	if (pathTarget == null) {
		targetTree.setSelectionPath(null);
		return false;
	}
	targetTree.setSelectionPath(pathTarget);
	if (action == DnDConstants.ACTION_COPY) {
		return false;
	} else if (action == DnDConstants.ACTION_MOVE) {
		Object targetNode = pathTarget.getLastPathComponent();
		return canMove(draggedNode, targetNode);
	} else {
		return false;
	}
}
 
Example #5
Source File: RTreeTest.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
public void singleNodeSelected() throws Throwable, InvocationTargetException {
    final JTree tree = (JTree) ComponentUtils.findComponent(JTree.class, frame);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    siw(new Runnable() {
        @Override
        public void run() {
            tree.expandRow(0);
            tree.setSelectionRow(0);
        }
    });
    final LoggingRecorder lr = new LoggingRecorder();
    siw(new Runnable() {
        @Override
        public void run() {
            Rectangle rowBounds = tree.getRowBounds(0);
            RTree rTree = new RTree(tree, null, rowBounds.getLocation(), lr);
            rTree.mouseButton1Pressed(null);
        }
    });
    Call call = lr.getCall();
    AssertJUnit.assertEquals("click", call.getFunction());
    AssertJUnit.assertEquals("/Root Node", call.getCellinfo());
}
 
Example #6
Source File: CTagTreeCellRenderer.java    From binnavi with Apache License 2.0 6 votes vote down vote up
@Override
public Component getTreeCellRendererComponent(final JTree tree,
    final Object value,
    final boolean sel,
    final boolean expanded,
    final boolean leaf,
    final int row,
    final boolean hasFocus) {
  final boolean selected = m_lastSelectionNode != null &&
      ((DefaultMutableTreeNode) value).getUserObject() == m_lastSelectionNode.getUserObject();

  super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, selected);

  setForeground(DEFAULT_FOREGROUND_COLOR);

  if (value instanceof CTagTreeNode) {
    renderTagTreeNode((CTagTreeNode) value);
  } else if (value instanceof CTaggedGraphNodeNode) {
    renderTaggedGraphNodeNode((CTaggedGraphNodeNode) value);
  } else if (value instanceof CTaggedGraphNodesContainerNode) {
    renderTaggedGraphNodesContainerNode((CTaggedGraphNodesContainerNode) value);
  }

  return this;
}
 
Example #7
Source File: MemberNodeTransferHandler.java    From binnavi with Apache License 2.0 6 votes vote down vote up
private static List<TypeMemberTreeNode> getSelectedNodesSorted(final JTree tree) {
  final List<TypeMemberTreeNode> nodes = Lists.newArrayList();
  for (final TreePath path : tree.getSelectionPaths()) {
    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
    if (node instanceof TypeMemberTreeNode) {
      nodes.add((TypeMemberTreeNode) node);
    } else {
      return Lists.newArrayList();
    }
  }
  Collections.sort(nodes, new Comparator<TypeMemberTreeNode>() {
    @Override
    public int compare(final TypeMemberTreeNode node0, final TypeMemberTreeNode node1) {
      return node0.getTypeMember().compareTo(node1.getTypeMember());
    }
  });

  return nodes;
}
 
Example #8
Source File: OurTree.java    From org.alloytools.alloy with Apache License 2.0 6 votes vote down vote up
/**
 * This method is called by Swing to return an object to be drawn.
 */
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded, boolean isLeaf, int row, boolean isFocused) {
    String string = tree.convertValueToText(value, isSelected, expanded, isLeaf, row, isFocused);
    this.isFocused = isFocused;
    this.isSelected = isSelected;
    setText(string);
    setForeground(UIManager.getColor(isSelected ? "Tree.selectionForeground" : "Tree.textForeground"));
    preferredHeight = 0; // By default, don't override width/height
    if (do_isDouble(value)) {
        Dimension d = super.getPreferredSize();
        preferredWidth = d.width + 3;
        preferredHeight = d.height * 2;
    }
    return this;
}
 
Example #9
Source File: RobotTreeCellRenderer.java    From RobotBuilder with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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);
    RobotComponent comp = (RobotComponent) value;

    if (comp.isValid()) {
        setForeground(Color.black);
    } else {
        setForeground(Color.red);
    }

    if (comp.supportsChildren() && leaf) {
        setIcon(getOpenIcon());
    }

    return this;
}
 
Example #10
Source File: DualProgramTest.java    From ghidra with Apache License 2.0 6 votes vote down vote up
@Test
public void testEscapeOpenSecondProgram() throws Exception {

	restoreProgram(diffTestP2);
	loadProgram(diffTestP1);
	launchDiffByAction();
	Window win = waitForWindow("Select Other Program");
	assertNotNull(win);
	waitForSwing();

	Component comp = getComponentOfType(win, JComboBox.class);
	assertNotNull(comp);

	JTree tree = findComponent(win, JTree.class);
	TreeTestUtils.selectTreeNodeByText(tree, "DiffTestPgm2");
	triggerActionKey(comp, 0, KeyEvent.VK_ESCAPE);
	waitForSwing();
	assertNull(fp2.getTopLevelAncestor());

	win = getWindow("Select Other Program");
	assertNull(win);
	closeProgram();
	assertNull(cb.getCurrentLocation());
}
 
Example #11
Source File: PopupInstantiateTemplate.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isEnableForComponent(Component invoker) {
    if (invoker.getName() != null && invoker.getName().equals(ScriptsListPanel.TREE)) {
        try {
            JTree tree = (JTree) invoker;
            ScriptNode node = (ScriptNode) tree.getLastSelectedPathComponent();

            if (node == null
                    || !node.isTemplate()
                    || node.getUserObject() == null
                    || !(node.getUserObject() instanceof ScriptWrapper)) {
                return false;
            }

            if (((ScriptWrapper) node.getUserObject()).getEngine() == null) {
                return false;
            }

            return extension.getScriptsPanel().getSelectedScript() != null;
        } catch (Exception e) {
        }
    }
    return false;
}
 
Example #12
Source File: RTree.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
private String getTextForNode(JTree tree, int row) {
    TreePath treePath = tree.getPathForRow(row);
    if (treePath == null) {
        return row + "";
    }
    StringBuilder sb = new StringBuilder();
    int start = tree.isRootVisible() ? 0 : 1;
    Object[] objs = treePath.getPath();
    for (int i = start; i < objs.length; i++) {
        String pathString;
        if (objs[i].toString() == null) {
            pathString = "";
        } else {
            pathString = escapeSpecialCharacters(getTextForNodeObject(tree, objs[i]));
        }
        sb.append("/" + pathString);
    }
    return sb.toString();
}
 
Example #13
Source File: CertificateTreeCellRend.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the rendered cell for the supplied value.
 *
 * @param jtrHierarchy
 *            The JTree
 * @param value
 *            The value to assign to the cell
 * @param isSelected
 *            True if cell is selected
 * @param isExpanded
 *            True if cell is expanded
 * @param leaf
 *            True if cell is a lesaf
 * @param row
 *            The row of the cell to render
 * @param hasFocus
 *            If true, render cell appropriately
 * @return The renderered cell
 */
@Override
public Component getTreeCellRendererComponent(JTree jtrHierarchy, Object value, boolean isSelected,
		boolean isExpanded, boolean leaf, int row, boolean hasFocus) {
	JLabel cell = (JLabel) super.getTreeCellRendererComponent(jtrHierarchy, value, isSelected, isExpanded, leaf,
			row, hasFocus);

	DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) value;

	Object userObject = treeNode.getUserObject();

	if (userObject instanceof X509Certificate) {
		X509Certificate cert = (X509Certificate) userObject;

		cell.setText(X509CertUtil.getShortName(cert));

		ImageIcon icon = new ImageIcon(getClass().getResource(
				"images/certificate_node.png"));
		cell.setIcon(icon);

		cell.setToolTipText(X500NameUtils.x500PrincipalToX500Name(cert.getSubjectX500Principal()).toString());
	}

	return cell;
}
 
Example #14
Source File: CheckBoxTreeCellRenderer.java    From SmartIM with Apache License 2.0 6 votes vote down vote up
/**
 * 返回的是一个<code>JPanel</code>对象,该对象中包含一个<code>JCheckBox</code>对象 和一个
 * <code>JLabel</code>对象。并且根据每个结点是否被选中来决定<code>JCheckBox</code> 是否被选中。
 */
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
    String stringValue = tree.convertValueToText(value, selected, expanded, leaf, row, hasFocus);
    setEnabled(tree.isEnabled());
    if (value instanceof CheckBoxTreeNode) {
        check.setSelected(((CheckBoxTreeNode)value).isSelected());
    }
    label.setFont(tree.getFont());
    label.setText(stringValue);
    label.setSelected(selected);
    label.setFocus(hasFocus);
    if (leaf)
        label.setIcon(UIManager.getIcon("Tree.leafIcon"));
    else if (expanded)
        label.setIcon(UIManager.getIcon("Tree.openIcon"));
    else
        label.setIcon(UIManager.getIcon("Tree.closedIcon"));

    return this;
}
 
Example #15
Source File: MultiTreeUI.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invokes the <code>stopEditing</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public boolean stopEditing(JTree a) {
    boolean returnValue =
        ((TreeUI) (uis.elementAt(0))).stopEditing(a);
    for (int i = 1; i < uis.size(); i++) {
        ((TreeUI) (uis.elementAt(i))).stopEditing(a);
    }
    return returnValue;
}
 
Example #16
Source File: CModuleInitializeAction.java    From binnavi with Apache License 2.0 5 votes vote down vote up
public CModuleInitializeAction(final JTree projectTree, final INaviModule[] modules) {
  super(generateMenuEntryName(modules));

  m_projectTree =
      Preconditions.checkNotNull(projectTree, "IE01901: Project tree argument can not be null");
  m_modules =
      Preconditions.checkNotNull(modules, "IE01902: Module argument can't be null").clone();

  putValue(ACCELERATOR_KEY, HotKeys.INITIALIZE_MODULE_ACCELERATOR_KEY.getKeyStroke());
  putValue(MNEMONIC_KEY, (int) "HK_MENU_INITIALIZE_MODULE".charAt(0));
}
 
Example #17
Source File: MultiTreeUI.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invokes the <code>getPathBounds</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public Rectangle getPathBounds(JTree a, TreePath b) {
    Rectangle returnValue =
        ((TreeUI) (uis.elementAt(0))).getPathBounds(a,b);
    for (int i = 1; i < uis.size(); i++) {
        ((TreeUI) (uis.elementAt(i))).getPathBounds(a,b);
    }
    return returnValue;
}
 
Example #18
Source File: SwingSet3TreeDemo.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
private void initComponents() {
    TreeDemo demo = new TreeDemo();
    JTree tree = (JTree) ComponentUtils.findComponent(JTree.class, demo);
    DefaultMutableTreeNode root = (DefaultMutableTreeNode) tree.getModel().getRoot();
    root.setUserObject("Root node [] , / Special");
    Container contentPane = getContentPane();
    contentPane.setLayout(new BorderLayout());
    contentPane.add(new JButton("Click-Me"), BorderLayout.NORTH);
    contentPane.add(demo, BorderLayout.CENTER);
    setSize(640, 480);
    setLocation(100, 100);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
 
Example #19
Source File: DependencyViewerStandalone.java    From gradle-view with Apache License 2.0 5 votes vote down vote up
public void updateView(GradleNode rootDependency, GradleNode selectedDependency) {
    // TODO replace this hack with something that populates the GradleNode graph

    DefaultMutableTreeNode fullRoot = new DefaultMutableTreeNode(new GradleNode("Project Dependencies"));
    if(rootDependency == null) {
        DefaultMutableTreeNode loading = new DefaultMutableTreeNode(new GradleNode("Loading..."));
        fullRoot.add(loading);
    } else {
        DefaultMutableTreeNode flattenedRoot = convertToSortedTreeNode(rootDependency);
        DefaultMutableTreeNode hierarchyRoot = convertToHierarchyTreeNode(rootDependency);
        fullRoot.add(flattenedRoot);
        fullRoot.add(hierarchyRoot);
    }

    TreeModel treeModel = new DefaultTreeModel(fullRoot);
    final JTree fullTree = new JTree(treeModel);
    fullTree.setCellRenderer(dependencyCellRenderer);

    // expand path for first level from root
    //fullTree.expandPath(new TreePath(hierarchyRoot.getNextNode().getPath()));

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            if(gradleBaseDir != null) {
                setTitle(TITLE + " - " + gradleBaseDir);
            }
            splitter.setLeftComponent(new JScrollPane(fullTree));
            splitter.setRightComponent(new JScrollPane(information));
            splitter.setDividerLocation(0.75);
        }
    });
}
 
Example #20
Source File: BrowserViewSupport.java    From visualvm with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Class getColumnClass(int column) {
    switch (column) {
        case 0: return JTree.class;
        case 1: return String.class;
        case 2: return Long.class;
        default: return null;
    }
}
 
Example #21
Source File: JTreeOperator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps {@code JTree.setInvokesStopCellEditing(boolean)} through queue
 */
public void setInvokesStopCellEditing(final boolean b) {
    runMapping(new MapVoidAction("setInvokesStopCellEditing") {
        @Override
        public void map() {
            ((JTree) getSource()).setInvokesStopCellEditing(b);
        }
    });
}
 
Example #22
Source File: GUIBrowser.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void expandAll(JTree tree, TreePath path) {
    tree.expandPath(path);
    TreeModel model = tree.getModel();
    Object lastComponent = path.getLastPathComponent();
    for (int i = 0; i < model.getChildCount(lastComponent); i++) {
        expandAll(tree,
                path.pathByAddingChild(model.getChild(lastComponent, i)));
    }
}
 
Example #23
Source File: MultiTreeUI.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the <code>getPathForRow</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public TreePath getPathForRow(JTree a, int b) {
    TreePath returnValue =
        ((TreeUI) (uis.elementAt(0))).getPathForRow(a,b);
    for (int i = 1; i < uis.size(); i++) {
        ((TreeUI) (uis.elementAt(i))).getPathForRow(a,b);
    }
    return returnValue;
}
 
Example #24
Source File: MultiTreeUI.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the <code>getPathBounds</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public Rectangle getPathBounds(JTree a, TreePath b) {
    Rectangle returnValue =
        ((TreeUI) (uis.elementAt(0))).getPathBounds(a,b);
    for (int i = 1; i < uis.size(); i++) {
        ((TreeUI) (uis.elementAt(i))).getPathBounds(a,b);
    }
    return returnValue;
}
 
Example #25
Source File: MultiTreeUI.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Invokes the <code>getPathBounds</code> method on each UI handled by this object.
 *
 * @return the value obtained from the first UI, which is
 * the UI obtained from the default <code>LookAndFeel</code>
 */
public Rectangle getPathBounds(JTree a, TreePath b) {
    Rectangle returnValue =
        ((TreeUI) (uis.elementAt(0))).getPathBounds(a,b);
    for (int i = 1; i < uis.size(); i++) {
        ((TreeUI) (uis.elementAt(i))).getPathBounds(a,b);
    }
    return returnValue;
}
 
Example #26
Source File: TreeMouseAdapter.java    From openAGV with Apache License 2.0 5 votes vote down vote up
@Override
public void mousePressed(MouseEvent e) {
  JTree objectTree = treeView.getTree();
  TreePath selPath = objectTree.getPathForLocation(e.getX(), e.getY());
  if (selPath == null) {
    if (e.getButton() == MouseEvent.BUTTON3) {
      showPopupMenu(e.getX(), e.getY());
    }
  }
  else {
    UserObject userObject = getUserObject(selPath);

    if (e.getButton() == MouseEvent.BUTTON3) {
      evaluateRightClick(e, userObject, treeView.getSelectedItems());
    }
    else if (e.getButton() == MouseEvent.BUTTON1) {

      //This Method tells the OpenTCSView what elements are currently selected
      ((AbstractUserObject) userObject).selectMultipleObjects();

      if (e.getClickCount() == 2) {
        userObject.doubleClicked();
      }

    }

  }

}
 
Example #27
Source File: JTreeOperator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps {@code JTree.getLeadSelectionRow()} through queue
 */
public int getLeadSelectionRow() {
    return (runMapping(new MapIntegerAction("getLeadSelectionRow") {
        @Override
        public int map() {
            return ((JTree) getSource()).getLeadSelectionRow();
        }
    }));
}
 
Example #28
Source File: AlertReportExportMenuItem.java    From zap-extensions with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isEnableForComponent(Component invoker) {
    if (invoker.getName() != null && "treeAlert".equals(invoker.getName())) {
        JTree tree = (JTree) invoker;
        if (tree.getLastSelectedPathComponent() != null) {
            DefaultMutableTreeNode node =
                    (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
            this.treeAlert = tree;
            if (!node.isRoot()) {
                return true;
            }
        }
    }
    return false;
}
 
Example #29
Source File: JTreeOperator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps {@code JTree.addSelectionPath(TreePath)} through queue
 */
public void addSelectionPath(final TreePath treePath) {
    runMapping(new MapVoidAction("addSelectionPath") {
        @Override
        public void map() {
            ((JTree) getSource()).addSelectionPath(treePath);
        }
    });
}
 
Example #30
Source File: ConfigTree.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
    DefaultMutableTreeNode node = ((DefaultMutableTreeNode)value);
    Object o = node.getUserObject();
    setText(o.toString());
    setOpaque(false);
    setToolTipText(null);
    if (o instanceof ConfigEntryNode) {
        ConfigEntryNode entry = (ConfigEntryNode)o;
        String key = entry.getKey();
        StringBuilder problems = new StringBuilder();
        for (ConfigConstraint constraint : config.getViolatedConstraints()) {
            if (constraint.getKeys().contains(key)) {
                if (problems.length() != 0) {
                    problems.append("\n");
                }
                problems.append(constraint.getDescription());
            }
        }
        if (problems.length() != 0) {
            setBackground(Color.RED);
            setOpaque(true);
            setToolTipText(problems.toString());
        }
    }
    return this;
}