我可以使用以下代码检测何时鼠标悬停在JTree的文本部分上。我还想检测用户何时将鼠标悬停在JTree文本左侧的图标上,该图标用于展开/折叠内容并相应地更改光标。我该怎么做?
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
public class Testing {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTree tree = new JTree(buildTree());
tree.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
TreePath tp = ((JTree) e.getSource()).getPathForLocation(e.getX(), e.getY());
if (tp != null) {
((JTree) e.getSource()).setCursor(new Cursor(Cursor.HAND_CURSOR));
} else {
((JTree) e.getSource()).setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}
});
frame.add(panel);
panel.add(tree);
frame.setSize(new Dimension(200, 200));
frame.setVisible(true);
}
public static DefaultMutableTreeNode buildTree() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode subOne = new DefaultMutableTreeNode("Test1");
DefaultMutableTreeNode leafOne = new DefaultMutableTreeNode("Leaf");
DefaultMutableTreeNode subTwo = new DefaultMutableTreeNode("Test2");
subOne.add(leafOne); //Drop down button should detect hover over
root.add(subOne);
root.add(subTwo);
return root;
}
}
森林海
相关分类