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.getContentPane().add(new JScrollPane(test.getTree()));

class TreeScanner extends MouseMotionAdapter
    static int lastSelected=-1;

    public void mouseExited(MouseEvent e){
       JTree tree=(JTree) e.getSource();

    public void mouseMoved(MouseEvent e){
       JTree tree=(JTree) e.getSource();
       int selRow=tree.getRowForLocation(e.getX(), e.getY());
       else if(selRow!=lastSelected){

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


, , , ,

  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: Logo

You are commenting using your 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: