How to select a node in a JTree by name

I have a JTree in my program. I want to programmatically set one of these nodes selected by the name of the node. I do not know how to do this. I read the "How to use trees", but no help
Thanks!

I have a JTree and each node on the JTree has a string name. I also have a JEditorPane that lists all these names at start up. If the user clicks on one of these names, I want to catch the HyperlinkEvent and automatically select that node in the JTree.
So in short, I have the String name of the node that I want to programatically select.
Thanks!

Similar Messages

  • How to allow multiple selection of nodes in a JTree

    How to allow multiple selection of nodes in a JTree ?
    Thanks
    S.Satish

    By default when you create new instance og JTree the selection model is multiple selection. And if you want to change it you use next:
    tee.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
    or
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    Hope will help!

  • Tree Bean - how to select a node?

    Can someone help how to select a node of the Tree based on the key programmatically?

    Hi there..
    I use a code like this..
    [Bindable] public var selectedNode:XML;
    [Bindable] public var mynewVar:String;
    public function treeChanged(event:ListEvent) : void   {  
    selectedNode = Tree(event.target).selectedItem as XML;
    mynewVar = selectedNode.@nameofNode;
    Cheers!

  • Selectively editing nodes in a JTree

    I need to make certain nodes in a JTree editable, without making every node in the tree editable. How can I accomplish this?

    Is there some kind of method in a JTree or a DefaultMutableTreeNode that I can call to select the node's text and be able to change it?Hmm. And you did read the API for JTree looking for such methods before you posted here, didn't you?
    So tell us which methods you found to be likely candidates.
    db

  • How to highlight a node in a JTree???

    I am trying to highlight (actually set the Font to Bold) one node of a JTree when an TreeSelectionEvent occurs (valueChanged method). The node to be highlighted can be different than the one selected.
    Thanks for your help.
    JavaSan

    To control the appearance of tree nodes, you need to write a TreeCellRenderer. Check Sun's tutorial on how to use trees (there's a link to it in the API documentation for JTree). The signature of the method you need to implement is this:
    public Component getTreeCellRendererComponent(
        JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus)so as you can see, you can vary the appearance of the node based on any of the parameters of that method.

  • Select multiple nodes in a JTree a right click

    Hi all,
    I've a JTree and I'd like to allow the user select some nodes (one or more) right click and than show a popupMenu.
    This behavior seems not to be easy, because if I select a single node (right clicking on it) the node does not appear selected ; I need to select it left clicking and than everything works fine.
    I read some posts found in the forum and the solution seems to be :
    - attach a mouseListener to the JTree
    - get the TreePath of the node selected
    - force the selection on the node with setSelectionPath(TreePath)
    This works fine if you need to select only one node, cause if you have to select more, you simply cannot.
    I wonder a so obvious behavior is so hard to achieve.
    I hope somebody out there had made the magic.
    Any help would be appreciated.
    Flavio Palumbo

    Hi Darryl,
    I wrote the test case below.
    Using the methods you suggested it works almost fine.
    The only behavior not desired is when you select a range (shift or control), release the key an than right click ; in this case remains selected the only node you clicked on ; to select the range clicking with the right button, you have to keep pressed the key.
    Any hint would be appreciated.
    Flavio
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPopupMenu;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    public class TestTree {
        JTree jtr = null;
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new TestTree();
        public TestTree() {
            JFrame jf = new JFrame();
            jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            try {
                javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                javax.swing.SwingUtilities.updateComponentTreeUI(jf);
            } catch (Throwable e) {
            jf.setPreferredSize(new java.awt.Dimension(200, 560));
            javax.swing.JScrollPane js = new javax.swing.JScrollPane();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
            jtr = new JTree(root);
            jtr.addMouseListener(new TestTreeML());
            js.setViewportView(jtr);
            jf.getContentPane().add(js);
            for (int i = 0; i < 20; i++) {
                DefaultMutableTreeNode nodoFiglio = new DefaultMutableTreeNode("nodo" + i);
                ((DefaultTreeModel) jtr.getModel()).insertNodeInto(nodoFiglio, root, root.getChildCount());
            jf.pack();
            jf.setVisible(true);
        public class TestTreeML extends MouseAdapter {
            @Override
            public void mousePressed(MouseEvent e) {
            @Override
            public void mouseClicked(MouseEvent e) {
                try {
                    if (!e.getSource().equals(jtr)) {
                        return;
                    TreePath tpSel = jtr.getPathForLocation(e.getX(), e.getY());
                    if (tpSel == null) {
                        return;
                    int i = 0;
                    final DefaultMutableTreeNode node = (DefaultMutableTreeNode) tpSel.getLastPathComponent();
                    TreePath[] tpExisting = null;
                    if (e.isControlDown() || e.isShiftDown()) {
                        System.out.println("control/shift");
                        TreePath[] tpEx = jtr.getSelectionPaths();
                        tpExisting = java.util.Arrays.copyOfRange(tpEx, 0, tpEx.length + 1);
                        i = tpEx.length;
                    } else {
                        tpExisting = new TreePath[1];
                    tpExisting[i] = tpSel;
                    jtr.setSelectionPaths(tpExisting);
                    if (e.getClickCount() == 2) {
                        System.out.println("double click on " + node.getUserObject());
                    if (javax.swing.SwingUtilities.isRightMouseButton(e)) {
                        if (!e.isControlDown()) {
                            jtr.setSelectionPath(tpSel);
                        JPopupMenu menu = new JPopupMenu();
                        JMenuItem it0 = new JMenuItem("Option1");
                        it0.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                System.out.println("Option1 on " + node.getUserObject());
                        menu.add(it0);
                        JMenuItem it1 = new JMenuItem("Option2");
                        it1.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                                System.out.println("Option2 on " + node.getUserObject());
                        menu.add(it1);
                        menu.show(jtr, e.getX(), e.getY());
                } catch (Throwable t) {
    }

  • Selecting a node in a JTree knowing his path

    Hello for all,
    I'm trying to select a specific node in a JTree component by clicking a button.. this is my code :
    private DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode("root");
    private DefaultTreeModel treeModel = new DefaultTreeModel(treeNode);
    private JTree tree = new JTree(treeModel);
    private JButton button = new JButton("Select");
    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("child1");
    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("child2");
    child1.add(new DefaultMutableTreeNode("child11"));
    treeNode.add(child1);
    treeNode.add(child2);
    button.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        TreePath path = new TreePath(new Object[]{"root", "child1"});               
        tree.setExpandsSelectedPaths(true);
        tree.scrollPathToVisible(path);
    });as you can see, I want to select the node with the path "root/child1"..
    but I'm getting this exception : Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.tree.TreeNode..
    any ideas ?

    You will want to read the second sentence in the TreePath comments section.
    Also, read the second sentence in the TreePath Method Detail section for the
    getLastPathComponent method.
    With these clues &#8212; try getting a TreePath from the tree you are working with.
    For example, you can try something like tree.getPathForRow(row) using the
    visible row index of "child1". Since the TreePath returned comes from the tree
    it will understand what to do with it. You can check the class name of the
    components that are returned in the TreePath to confirm this. And it will
    explain the exception you quoted.

  • How to select a node by name in a Tree?

    Hi,
    I require some help:
    I want to select a  Node of a Tree "myTree" by his displayed name.
    I can select a Node by using "myTree.selectedIndex = idx". But how do I get the current Index of that Node?
    Thx

    Hi there..
    I use a code like this..
    [Bindable] public var selectedNode:XML;
    [Bindable] public var mynewVar:String;
    public function treeChanged(event:ListEvent) : void   {  
    selectedNode = Tree(event.target).selectedItem as XML;
    mynewVar = selectedNode.@nameofNode;
    Cheers!

  • How to use custom nodes in a JTree without reinventing the wheel?

    Hello,
    Each node contains two JTextAreas in a Box layout and a few JButtons.
    I wish to display these nodes in a JTree.
    Reading the tutorial, it seems I would have to reimplement the TreeModel, TreeCellRenderer/Editor, MutableTreeNode interfaces etc.
    Can I use the DefaultTreeModel, and other standard widgets (great stuff!) to minimize the amount of reimplementation I must do. aka avoid reinventing the wheel? I was thinking of extending my node from the DefaultMutableTreeNode class - however it does not display the nodes with the TextAreas, buttons etc.
    any help appreciated.
    thanks,
    Anil

    was able to fix it over here:
    http://forum.java.sun.com/thread.jspa?messageID=4089777

  • How do I make nodes in my JTree render as JTextPanes ?

    As a newbie to Java, I developed an application which started out by by having a user select a value in a JList and associated information was formatted nicely into a JTextPane (really it is just making some bold/italic/regular font switches).
    I now think it may be more visually appealing to represent the whole thing as a JTree, and the user would just click the +/- to access the associated information.
    So I would like substitute the JTree for the JList, while keep my nicely formatted JTextPane and am a bit stuck. I'd like each item in the JList to be a node and the information is going to be a leaf.
    Searching through the forums and other tutorials it I think I need to create a TreeCellRenderer that uses my JTextPane.
    Aside from advice such as Prior Planning Prevents Poor Performance, can someone give me a gentle kick in the right direction ? Pseudo-code or links would be great !
    Thanks in advance.

    Hi codingMonkey,
    I've looked at both of those (previously) but I've not got enough experience to figure out the coding bits for my application.
    So lets say I wanted to hack the JTextPane example here http://java.sun.com/docs/books/tutorial/uiswing/components/editorpane.html and put a simple JTree in its place with three nodes and use the provided JTextPane as a text for the leafs.
    I think the important bits (except are addStylesToDocument) are this:
    private JTextPane createTextPane() {
            String[] initString =
                    { "This is an editable JTextPane, ",            //regular
                      "another ",                                   //italic
                      "styled ",                                    //bold
                      "text ",                                      //small
                      "component, ",                                //large
                      "which supports embedded components..." + newline,//regular
                      " " + newline,                                //button
                      "...and embedded icons..." + newline,         //regular
                      " ",                                          //icon
                      newline + "JTextPane is a subclass of JEditorPane that " +
                        "uses a StyledEditorKit and StyledDocument, and provides " +
                        "cover methods for interacting with those objects."
            String[] initStyles =
                    { "regular", "italic", "bold", "small", "large",
                      "regular", "button", "regular", "icon",
                      "regular"
            JTextPane textPane = new JTextPane();
            StyledDocument doc = textPane.getStyledDocument();
            addStylesToDocument(doc);
            try {
                for (int i=0; i < initString.length; i++) {
                    doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    } catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    I don't really understand the TreeCellRenderer API link you sent and how to link the above JTextPane to the TreeCellRenderer.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to select multiple nodes, which are not next to each other,  in a tree?

    The following code suppose to allow user select any combination of nodes (because of DISCONTIGUOUS_TREE_SELECTION), however, I can only select nodes which are next to each other. Can some one told me how to make this DISCONTIGUOUS_TREE_SELECTION work?
    Thank you very much!
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TestTree extends JFrame {
    public TestTree() {
    super();
    setBounds(0,0,500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTree tree = new JTree();
    getContentPane().add(tree);
    TreeSelectionModel model = new DefaultTreeSelectionModel();
    model.setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    tree.setSelectionModel(model);
    public static void main(String [] args) {
    TestTree test = new TestTree();
    test.show();

    In Windows you hold down the Ctrl key while clicking on the nodes you want to select. Don't know the equivalent in other environments.

  • How to select the node in structure view from selected xml page item

    Hi All,
    I have imported the xml file. Now drag and dropped the root node in the documentt.Now i select a item from it.When i select an item, i need the node in the structure view to get selected.
    In Indesign we have an menu option "Select in structure".
    How to go about it?
    Regards
    Sakthi

    Hi All,
    I have imported the xml file. Now drag and dropped the root node in the documentt.Now i select a item from it.When i select an item, i need the node in the structure view to get selected.
    In Indesign we have an menu option "Select in structure".
    How to go about it?
    Regards
    Sakthi

  • How to get a node  in a Jtree on which right mouse button is clicked

    I am dealing with a situation in which whenever tree component is clicked by right mouse button I am needed to get the tree node on which right mouse button was clicked.

    MouseEvent e = ...
    TreePath path = tree.getPathForLocation(e.getX(), e.getY());
    Object nodeClickedOn = path.getLastPathComponent();Or something along those lines.

  • How to remove a node from  a Jtree?

    I tried giving this to move a node from one parent node to other parent node.
    IconNodeClass userObject = (IconNodeClass)tr.getTransferData(TransferableDataItem.Image_Tree_Node_Flavor);
    IconNodeClass node = (IconNodeClass)path.getLastPathComponent();
    IconNodeClass newNode = new IconNodeClass(userObject);
    DefaultTreeModel model = (DefaultTreeModel)getModel();
    IconNodeClass oldParentNode = (IconNodeClass)userObject.getParent();
    Object oldParent = oldParentNode.getUserObject();
    Object newParent = node.getUserObject();
    if(oldParent.equals(newParent)) {
    model.insertNodeInto(newNode, node, 0);
    if(oldParentNode != null) {
    oldParentNode.remove(newNode);
    model.reload(oldParentNode);
    }

    what happened next ?????

  • How to select tree node with enter key instead of mouse click

    hia i have tree in forms 10g i can get node value when i click mouse on node but i want same with enter key which is not working any idea.
    thanx

    I'm afraid you have hit Bug 4509399
    If you have metalink access you should check Note:331369.1
    This bug has been around for the 10g R2 10.1.2.0.2 base release, which was propagated from Installing Patch 9.0.4.2 or from 10g R1 base release. You need to apply the latest patch or a one-off fix Patch 4509399
    Tony

Maybe you are looking for

  • No connection to new install of WSUS, 404 errors in log

    I am attempting to move WSUS from a functional Windows 2008 R2 server to a Windows Server 2012 R2 environment.  There are no connection problems to the old server.  However, I cannot get clients - including the Win2012 server itself - to connect to W

  • How to find Document flow / Relationships to a support message

    Hi Friends, I am new to Solution manager. I would like to know how to find Document flow of a Support message. For example I have a Support message, there are few Change requests and tasks linked to it. This can be viewed from CRMD_ORDER transaction

  • Migration Assistant

    I just bought a new MBP. I already own a 3 year old Mac Pro. Before I migrate and potentially screw something up (I am a recovering PC user), I have some questions. 1. can I use the USB/mini cable to connect to my Time Machine HD? It seems to be comm

  • My email message disappears off the page before it is sent or saved.

    Sometimes my email message disappears (zooms to the right) before it is sent or saved (I use Safari).  How can I retrieve that message?

  • ITunes U: how do I turn off the 50 MB download limit for mobile data connections?

    Since I rarely have access to Wi-Fi networks I do actually want to download iTunes U content using mobile data. Videos (and even some slide decks) exceed the 50 MB limit that iTunes U will allow you to download over mobile data connections. How do I