Changing Background of JTree Nodes On Bringing Mouse Over Them

Here is a program which shows you how to change the background or foreground of a JTree node when cursor is brought over individual nodes.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

public class TreeTest
{
    private JTree getTree()
    {
        String[] birds = {
            // branches |<-- child leaf nodes -->|
            "hawks", "gray", "red-tailed", "rough-legged",
            "falcons", "harrier", "kestrel", "kite",
            "owls", "barred", "saw-whet", "snowy"
        };
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("birds");
        DefaultMutableTreeNode[] nodes = new DefaultMutableTreeNode[birds.length];
        for(int j = 0; j < nodes.length; j++)
            nodes[j] = new DefaultMutableTreeNode(birds[j]);
        for(int j = 0; j < 9; j += 4)
        {
            root.insert(nodes[j], j % 3);
            for(int k = j + 1; k < j + 4; k++)
                nodes[j].insert(nodes[k], k - j - 1);
        }
        DefaultTreeModel model = new DefaultTreeModel(root);
        JTree tree = new JTree(model);
        tree.addMouseMotionListener(new TreeScanner());
        return tree;
    }

    public static void main(String[] args)
    {
        TreeTest test = new TreeTest();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new JScrollPane(test.getTree()));
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
    }
}

class TreeScanner extends MouseMotionAdapter
{
    static int lastSelected=-1;

    @Override
    public void mouseExited(MouseEvent e){
       JTree tree=(JTree) e.getSource();
       lastSelected=-1;
       tree.clearSelection();
    }

    @Override
    public void mouseMoved(MouseEvent e){
       JTree tree=(JTree) e.getSource();
       int selRow=tree.getRowForLocation(e.getX(), e.getY());
       if(selRow==-1){
           tree.clearSelection();
           lastSelected=-1;
       }
       else if(selRow!=lastSelected){
           tree.setSelectionRow(selRow);
           lastSelected=selRow;
       }
    }
}

Originally posted by Craig Wood on coderanch.com and enhanced by me(Abhishek)

Advertisements

, , , ,

  1. #1 by trottel on March 15, 2012 - 8:33 PM

    Hm. The program does what the title says, but I have expected that no selection event is fired

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: