Java Swing How to - Forward mouseMoved() events to JTree nodes








Question

We would like to know how to forward mouseMoved() events to JTree nodes.

Answer

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/*from  w  w  w  .  j av a 2  s  .c  om*/
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreePath;

public class Main {
  public static void main(String[] args) {

    DefaultMutableTreeNode root = new DefaultMutableTreeNode(Boolean.TRUE);
    DefaultMutableTreeNode child1 = new DefaultMutableTreeNode(Boolean.FALSE);
    DefaultMutableTreeNode child2 = new DefaultMutableTreeNode(Boolean.FALSE);
    root.add(child1);
    root.add(child2);
    DefaultTreeModel model = new DefaultTreeModel(root);

    JTree tree = new JTree(model);
    tree.setCellRenderer(new TreeRenderer());

    tree.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        TreePath pathForLocation = tree.getPathForLocation(e.getX(), e.getY());
        Object lastPathComponent = pathForLocation.getLastPathComponent();
        if (lastPathComponent instanceof DefaultMutableTreeNode) {
          Boolean oldObject = (Boolean) ((DefaultMutableTreeNode) lastPathComponent)
              .getUserObject();
          ((DefaultMutableTreeNode) lastPathComponent)
              .setUserObject(!oldObject);
          model.nodeChanged((DefaultMutableTreeNode) lastPathComponent);
        }
      }
    });

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(new BorderLayout());
    frame.getContentPane().add(tree, BorderLayout.CENTER);
    frame.setSize(800, 600);
    frame.setVisible(true);
  }
}
class TreeRenderer implements TreeCellRenderer {
  private final JCheckBox checkbox = new JCheckBox();

  @Override
  public Component getTreeCellRendererComponent(JTree tree, Object value,
      boolean selected, boolean expanded, boolean leaf, int row,
      boolean hasFocus) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
    checkbox.setSelected((Boolean) node.getUserObject());
    checkbox.setText("Row:" + row);
    return checkbox;
  }
}