How to highlight JTree node without selecting it

Hello,
I want to highlight a Tree Node without selecting it.
Anybody having ideas as to how i can do it.
thanks in advance.
Reg,
sai

for what it's worth for anyone with the same problem, the problem was that the node was being regenerated as a different object so each time it went through the object wasn't the same and therefore had a new expanded value as default of false.

Similar Messages

  • How to highlight a node in a tree?

    i used setSelectionPath() . But it is highlighting the node's icon only(i.e by changing the color to lavender). I'm getting higlighted the node with setSelectionInterval(ind,ind) only. I want that higlighlighting to be with setselectionPath() . How to do?
    Appreciating any help
    Thanks.

    When I do a setSelectionPath the node-text is highlighted, not the icon. Anyways, do a custom treecellrenderer like this:
    public Component getTreeCellRendererComponent(.......) {
    if(selected == true) setBackground(somecolor)
    else setBackground (defaultcolor)
    if that describtion isnt sufficient try search the forum.

  • Expanding a JTree Node on selection

    Hi,
    I have a need to expand the node on selection in a JTree. I would like all the children to be recursively expanded and selected.
    I believe the code lies somewhere with in JTree's TreeSelectionListener.
    The code I have is as follows
    tree.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent evt)
    TreePath[] paths = evt.getPaths();
    for (int i=0; i<paths.length; i++)
    if (evt.isAddedPath(i))
    DataNode node = (DataNode)paths.getLastPathComponent();
    ArrayList aList = node.children();
    if( !aList.isEmpty() )
    for(int j = 0; j<aList.size(); j++)
    TreePath tp = paths[i].pathByAddingChild(aList.get(j));
    System.out.println(tp);
    tree.expandPath(tp);
    }//for
    }//public void ValueChanged
    This does not seem to solve the problem..
    Your comments or help is very much appreciated..
    thanks
    S

    it does work for me (i do it in an action). what doesn't work for you?
    thomas
      public RecursiveExpander() {
        menu = new JPopupMenu();
        JMenuItem expand = new JMenuItem("Expand Recursive");
        expand.addActionListener(this);
        menu.add(expand);
      public void mousePressed(MouseEvent e) {
        theTree = (JTree)e.getSource();
        currentPath = theTree.getPathForLocation(e.getX(), e.getY());
        if ((currentPath != null) &&
            !((TreeNode)currentPath.getLastPathComponent()).isLeaf() &&
            (e.getModifiers() == InputEvent.BUTTON3_MASK)) {
          menu.show(theTree, e.getX(), e.getY());
      public void actionPerformed(ActionEvent ae) {
        new Thread(this).start();
      public void run() {
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try { expand(currentPath); }
        catch (OutOfMemoryError oom) {
          System.gc();
          System.err.println("RecursiveExpander: " + oom);
          JOptionPane.showMessageDialog(null, "RecursiveExpander: " + oom, "Error", JOptionPane.ERROR_MESSAGE);
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      private void expand(TreePath path) {
        theTree.expandPath(path);
        TreeNode start = (TreeNode)path.getLastPathComponent();
        for (int i = 0; i < start.getChildCount(); i++) {
          TreeNode node = start.getChildAt(i);
          if (!node.isLeaf()) {
            expand(path.pathByAddingChild(node));
    }

  • How to change JTree nodes background?

    hello there
    i have a jtree which i set its background to red
    but the nodes background is still white
    why?and how to set the nodes background to red too?
    and how to remove the tree border
    because i tried setting it to null and it doesn't work?
    here is my code:
    package view;
    import java.awt.Color;
    import javax.swing.*;
    import javax.swing.tree.*;
    class TreeComponent{
      public static void main(String[] args) {
        JFrame frame = new JFrame("Creating a JTree Component!");
        DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Color", true);
        DefaultMutableTreeNode black = new DefaultMutableTreeNode("Black");
        DefaultMutableTreeNode blue = new DefaultMutableTreeNode("Blue");
        DefaultMutableTreeNode nBlue = new DefaultMutableTreeNode("Navy Blue");
        DefaultMutableTreeNode dBlue = new DefaultMutableTreeNode("Dark Blue");
        DefaultMutableTreeNode green = new DefaultMutableTreeNode("Green");
        DefaultMutableTreeNode white = new DefaultMutableTreeNode("White");
        parent.add(black);
        parent.add(blue);
        blue.add(nBlue);
        blue.add(dBlue);
        parent.add(green );
        parent.add(white);
        JTree tree = new JTree(parent);
        tree.setBackground(Color.red);
        tree.setBorder(null);
        frame.add(tree);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
        frame.setSize(200,200);
        frame.setVisible(true);
    }

    how to set the nodes background to red too?
    ((JComponent) tree.getCellRenderer()).setOpaque(true);[/code\
    how to remove the tree borderWhat border?
    db                                                                                                                                                                                                                                                                                                                                       

  • How to sort Jtree node?

    Now, I want to sort tree node by increasing.
    for example there are three child node:
    [20 -40][
    10 - 20]
    [30- 60].
    they are added to JTree node by different order.but are shown in increasingorder.
    like this:
    [10 - 20]
    [20 -40][
    [30- 60].
    how to control tree node.

    Implement the Comparable interface in t he userobject class and possibly the toString(0 as well.
    Ex.
    public class UserObject implements java.lang.Comparable{
    public int compareTo(Object obj) throws ClassCastException
    public String toString()

  • How to start / stop nodes without domain-controller / automatically on Win?

    Hi,
    we have a distributed installation of CMSDK 9.0.4.
    We have installed a 9.2.0.4 Database on Solaris and we are using the 10g(9.0.4) Infrastructure on Solaris with it.
    The first installation of CMSDK uses a J2EE-MidTier installation on the Solaris server and contains the CMSDK domain controller and a normal node with nfs protocol server running.
    The other installations are done on Win2003 Blades. Currently we are using two Blades. On each there is a J2EE-MidTier installation and within these we have installed CMSDK with HTTP-Node and normal node. We are using NTFS-Server within the normal nodes.
    The Blades are within one Domain and we have NLB-Cluster activated for both.
    The whole thing sounds complex, but it works fine. We only have some trouble regarding start/stop of the nodes:
    1. If the solaris backend fails, our cluster-configuration tries to stop and start cmsdk. While stopping cmsdk, all nodes - even those on the Win-Servers - are stopped. But starting does not bring em up again automatically.
    2. If a Windows Server is booted, the normal node does not start automatically.
    3. If one Windows Server is not available, the ifsctl check takes a very long time because it's trying to get information from the missing one.
    Is there a way to restart the domain controller and node on solaris without stopping the nodes on Windows?
    How can we start the windows nodes automatically after reboot?
    Is there a way to probably start the nodes without being managed / guarded by the domain controller?
    Thanks for help,
    Alex

    Try adding this script to your /etc/init.d directory:
    #!/bin/sh
    ifsctl start << EOF
    <ifsctl password>
    EOF
    Replace <ifsctl password> with the password that you would give at the prompt.
    It will complain about Inappropriate ioctl for device, but it works.

  • How to launch midlet straightaway without selecting

    I have only one midlet, how can I start the midlet without selecting from the list.

    I had the same problem and found that runtime errors (which won't be displayed) can cause this. In my case, I did not have a png file in the package and was listing it in the settings.
    At the same time, another application with similar settings as above ran smoothly.
    Just remember, you will always find weird bugs in evolving technologies.
    PS: Ever tried to use Vectors and Hashtables in an applet? you'll know what I mean :).

  • How to sort jTree Nodes

    Hi,
    I am interested in whats the easiest way to sort jTree Nodes alphabetically. Is there any Method to do this directly or may i use something like quicksort?
    Thanks for help
    Mirco

    Thanks Hamed,
    Well, I work in your code, and I post here.
      public static DefaultMutableTreeNode sortTree(DefaultMutableTreeNode root) {
                     for (int i =0; i<root.getChildCount()-1; i++) {
                              DefaultMutableTreeNode node = (DefaultMutableTreeNode) root.getChildAt(i);
                            String nt = node.getUserObject().toString();
                            for (int j=i+1;j<=root.getChildCount()-1;j++)
                                     DefaultMutableTreeNode prevNode = (DefaultMutableTreeNode) root.getChildAt(j);
                                        String np = prevNode.getUserObject().toString();
                                System.out.println(nt+" "+np);
                                if (nt.compareToIgnoreCase(np)>0) {
                                               root.insert(node, j);
                                             root.insert(prevNode, i);
                            if (node.getChildCount() > 0) {
                        node = sortTree(node);
                     return root;
        }and this code I used after include in jtree
      public  void jTreeSortingBegin()
              dn = (DefaultMutableTreeNode)treeModel.getRoot();
              treeModel.reload();
              dn = sortTree(dn);
              treeModel.reload(dn);
        }for exemple
      addObject(jTextField1.getText());
            jTreeSortingBegin();

  • 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.

  • How to highlight Tree node with a diff color

    I have created tree node and want to highlight Selected node with a different background color. Any Ideas how can we achieve that? -R

    It's an item on page 4 of the application that the blog example is taken from. The tree query:
    SELECT EMPLOYEE_ID AS ID
         , MANAGER_ID  AS PID
         , CASE
             WHEN EMPLOYEE_ID = :P4_EMPLOYEE_ID THEN
                 '<span style="color:white;background-color:blue;">'||
                 LAST_NAME||
                 '</span>'
             ELSE
                 LAST_NAME
           END AS NAME
         , 'f?p=&APP_ID.:4:'||:SESSION||'::NO::P4_EMPLOYEE_ID:'||EMPLOYEE_ID AS LINK
         , NULL        AS A1
         , NULL        AS A2
      FROM #OWNER#.EMPLOYEESgenerates leaf nodes that link to page 4, setting the value of P4_EMPLOYEE_ID. When page 4 is rendered, P4_EMPLOYEE_ID contains the ID of the clicked node, the page displays details of the employee with this ID, and the case expression in the tree query causes the corresponding display value to be highlighted.
    See the sections Managing Session State Values and Using f?p Syntax to Link Pages in the documentation to understand how to set session state values using URLs.
    http://download.oracle.com/docs/cd/E14373_01/appdev.32/e11838/concept.htm

  • How to set Jtree Nodes' name into TextField??

    Dear Sir:
    I have following code to select any file's name then put into TextField,
    see:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.io.File;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    public class JTreeSplitChooseDemo extends JPanel implements ActionListener{
        JFileChooser fc;
        JButton openButton, saveButton;
        JTextField jtf;
      public JTreeSplitChooseDemo() {
        final JTree tree;
        final JTextField jtf;
        JPanel jp= new JPanel();
        setPreferredSize(new Dimension(500,350));
        jp.setPreferredSize(new Dimension(500,300));
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
        DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
        top.add(a);
        DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
        a.add(a1);
        DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
        a.add(a2);
        DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
        top.add(b);
        DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
        b.add(b1);
        DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
        b.add(b2);
        DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
        b.add(b3);
        tree = new JTree(top);
        JScrollPane jsp = new JScrollPane(tree);
        jsp.setPreferredSize(new Dimension(500,300));
        tree.setPreferredSize(new Dimension(500,300));
        add(jsp, BorderLayout.CENTER);
        jtf = new JTextField("", 20);
        add(jtf, BorderLayout.SOUTH);
        tree.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent me) {
            TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
            if (tp != null)
              jtf.setText(tp.toString());
            else
              jtf.setText("");
      public JPanel JTreeText() {
             JPanel jp= new JPanel();
             JPanel jpanel= new JPanel();
             setPreferredSize(new Dimension(400,350));
             jp.setPreferredSize(new Dimension(400,300));
             JScrollPane jsp = new JScrollPane(jp);
             jsp.setPreferredSize(new Dimension(400,300));
             jpanel.add(jsp, BorderLayout.CENTER);
             jtf = new JTextField("", 20);
             fc = new JFileChooser();
             openButton = new JButton("Open a File...",new ImageIcon("images/hui.gif"));
             openButton.addActionListener(this);
             JPanel buttonPanel = new JPanel(); //use FlowLayout
             buttonPanel.add(openButton);
             //jp.add(buttonPanel, BorderLayout.PAGE_START);
             jp.add(buttonPanel, BorderLayout.NORTH);
             jp.add(jtf, BorderLayout.CENTER);
             return jpanel;
      public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.getContentPane().add(new JTreeSplitChooseDemo(), new BorderLayout().WEST);
        frame.getContentPane().add(new JTreeSplitChooseDemo().JTreeText(), new BorderLayout().CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 350);
        frame.setVisible(true);
    @Override
    public void actionPerformed(ActionEvent e) {
         //Handle open button action.
        if (e.getSource() == openButton) {
          int returnVal = fc.showOpenDialog(JTreeSplitChooseDemo.this);
          if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
             jtf.setText(file.getName());
          } else {
             jtf.add("Open command cancelled by user.", null);
    }For example, If i choose file : C:\temp\ftp\TestMyFile.txt
    after I press open button, then choose it, then, the file name TestMyFile.txt will be displayed in the textFiled.
    My problem is that I hope to choose any node in the JTree on the left Panel, then when I choose it, this JNode I selected will be displayed its name in the TextField.
    Not file, I need choose JNode,
    ie, B1 under B node, or A1 under A node, then B1 will be displayed in jtf.
    How to do this one??
    Can Guru throw some light??
    Thanks
    sunny

    Thanks, camickr.
    My fault not to explain detail.
    Actually I mean that I will use a dialog box(very much look like a file choose) that is something like a file chooser then I can browse over JTree first for any node then I can choose or select a node in this JTree, after select this node, its name is populated into text field. My one is I will use a JTree browser (something like that) to get a tree node.
    ie, this showOpenDialog will browse over JTree, not File system.
    I did not want to click on the node then this node name is populated into textField.
    the sample (http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html) shows that when I select a node, then its name was populated to a destination.

  • How to display a table without selecting the first row as default ?

    Hello All,
      Can someone advise on how I am able to display a table but with no row selected on initial display ? Currently, the table is being displayed with the first entry selected by default (The orange box is selected). Thank you very much.
    from
    Kwok Wei

    Javadoc for IWDNode says:
    public void clearSelection()
        Clears the Node's multiple selection; does not change the lead selection.
    public void setLeadSelection(int index)
        Sets the lead selection to the given index. It may be called with NO_SELECTION to reset (clear) the lead selection.
        Parameters:
            index - the index of the element
        Throws:
            ContextException - if caller tries to reset the selection, but selection is mandatory
            IndexOutOfBoundsException - if the given index is not within the element list
        See Also:
            getLeadSelection()
    Armin

  • How-To Add JTree nodes on Expanding

    I'm connecting to a database to retrieve information for my JTree, but when I populate my JTree it takes forever due to the table size I'm extracting from. (Big tree). Is there a way to wait until someone opens a folder to add nodes to it?
    Thanks for any help.

    Hi, another way you can thing about is to create your own Userobject and if the valueChanged you can populate your userObject in the TreeSelectionListener.
    The only thing your UserObject must have a toString method. so you can implement a Method which is populating your Sub-Tree direct in your UserObject by invoking it from the TreeSelectionListener.
    With getLastSelectedPathComponent() you can get the point where you have to add your children
    if you have allowed children. This should also work without your own UserObjects.
    I hope this helps.
    Greetings Michael

  • How do I highlight JTree selection ?

    Hi,
    How do you highlight the selected node in a JTree from code ?
    I am deleting a node and want to highlight the preceeding node. I select it via this code :-
    jTree.setSelectionPath( newSelectedPath);
    jTree.scrollPathToVisible( newSelectedPath);
    jTree.repaint();
    But that does not highlight the node.
    Many thanks in advance,
    Aaron

    With the Move tool selected, this seems to be the only way to enlarge a selection.
    What I'd want to do in Joshua's situation though is to draw a marquee around the clips I want to select. The inability to hold down shift or control and draw a second marquee to add more clips to a selection seems like a flaw! Is there a key combination or do I have to always select individual clips (or groups) after the initial selection?

  • How to highlight node in JTree?

    After the tree has been displayed, I want to highlight the nodes matching some certain keywords. How to implement that? Nothing useful is found in past threads.
    thanks.

    to take a wild guess:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public class HighlightTreeNodeTest {
      private final JTree tree       = new JTree();
      private final JTextField field = new JTextField("foo");
      private final JButton button   = new JButton();
      private final MyTreeCellRenderer renderer =
        new MyTreeCellRenderer(tree.getCellRenderer());
      public JComponent makeUI() {
        field.getDocument().addDocumentListener(new DocumentListener() {
          @Override public void insertUpdate(DocumentEvent e) {
            fireDocumentChangeEvent();
          @Override public void removeUpdate(DocumentEvent e) {
            fireDocumentChangeEvent();
          @Override public void changedUpdate(DocumentEvent e) {}
        tree.setCellRenderer(renderer);
        renderer.q = field.getText();
        fireDocumentChangeEvent();
        JPanel p = new JPanel(new BorderLayout(5, 5));
        p.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
        p.add(field, BorderLayout.NORTH);
        p.add(new JScrollPane(tree));
        return p;
      private void fireDocumentChangeEvent() {
        String q = field.getText();
        renderer.q = q;
        TreePath root = tree.getPathForRow(0);
        collapseAll(tree, root);
        if (!q.isEmpty()) searchTree(tree, root, q);
        tree.repaint();
      private static void searchTree(JTree tree, TreePath path, String q) {
        TreeNode node = (TreeNode)path.getLastPathComponent();
        if (node==null) return;
        if (node.toString().startsWith(q)) tree.expandPath(path.getParentPath());
        if (!node.isLeaf() && node.getChildCount()>=0) {
          Enumeration e = node.children();
          while (e.hasMoreElements())
            searchTree(tree, path.pathByAddingChild(e.nextElement()), q);
      private static void collapseAll(JTree tree, TreePath parent) {
        TreeNode node = (TreeNode)parent.getLastPathComponent();
        if (!node.isLeaf() && node.getChildCount()>=0) {
          Enumeration e = node.children();
          while (e.hasMoreElements()) {
            TreeNode n = (TreeNode)e.nextElement();
            TreePath path = parent.pathByAddingChild(n);
            collapseAll(tree, path);
        tree.collapsePath(parent);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new HighlightTreeNodeTest().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    class MyTreeCellRenderer extends DefaultTreeCellRenderer {
      private final TreeCellRenderer renderer;
      public String q;
      public MyTreeCellRenderer(TreeCellRenderer renderer) {
        this.renderer = renderer;
      @Override public Component getTreeCellRendererComponent(
          JTree tree, Object value, boolean isSelected, boolean expanded,
          boolean leaf, int row, boolean hasFocus) {
        JComponent c = (JComponent)renderer.getTreeCellRendererComponent(
            tree, value, isSelected, expanded, leaf, row, hasFocus);
        if (isSelected) {
          c.setOpaque(false);
          c.setForeground(getTextSelectionColor());
        } else {
          c.setOpaque(true);
          if (q!=null && !q.isEmpty() && value.toString().startsWith(q)) {
            c.setForeground(getTextNonSelectionColor());
            c.setBackground(Color.YELLOW);
          } else {
            c.setForeground(getTextNonSelectionColor());
            c.setBackground(getBackgroundNonSelectionColor());
        return c;
    }

Maybe you are looking for

  • Bw report,urgent

    rrmx: stock details report, this is std report.k, i want to excute n get the data for last month in excel sheet, for the excecution ,i want to submit in back ground,is there any possiblity to submit in background.(i wwant to execute this report in ba

  • Errors while creating Inspection plan using BAPI_INSPECTIONPLAN_CREATE

    Hi All, I am writing an upload tool for inspection plans. In this program I use bapi: BAPI_INSPECTIONPLAN_CREATE. I made an extraction of a excisting inspection plan with SXDA_TOOLS which uses the same bapi and filled the bapi structures with the sim

  • Report for reports

    Hi Experts, I have a requirement where I have to build a query for some BW querys i.e. I have to generate a Report Access History Log for define BW PP Reports. Following information required in the Log Report: 1) How often are these reports accessed

  • Error V0104 in BAPI_SALESORDER_SIMULATE

    Hello, While executing BAPI BAPI_SALESORDER_SIMULATE I end up with error V0104 and processing terminates. This has got to do with the screen sequence and entries are missing in table T185D. Is it not that this table has to be maintained using transac

  • Re: Broadband Suspended

    My broadband has been suspended incorrectly. My browser is being diverted to a BT page saying I have not paid a bill, but the bill is paid by direct debit, in "My BT", it clearly states date of the bill and that I do not need to do anything and the o