gpt4 book ai didi

java - 想要在 JTree 列出的元素上移动鼠标时更改光标

转载 作者:行者123 更新时间:2023-11-29 03:37:55 25 4
gpt4 key购买 nike

当光标仅在列出的元素上而不是整个组件上时,我想在鼠标移到 JTree 组件上时将光标更改为手形光标。

以下代码用于 Jlist 组件。我想要同样的 JTree,但是 JTree 没有 getCellBound()。还有其他办法吗?

final JList list = new JList(new String[] {"a","b","c"});
list.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
final int x = e.getX();
final int y = e.getY();
// only display a hand if the cursor is over the items
final Rectangle cellBounds = list.getCellBounds(0, list.getModel().getSize() - 1);
if (cellBounds != null && cellBounds.contains(x, y)) {
list.setCursor(new Cursor(Cursor.HAND_CURSOR));
} else {
list.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
}

@Override
public void mouseDragged(MouseEvent e) {
}
});

最佳答案

我猜你正在寻找这样的东西:

import java.awt.Cursor;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class TestTreeSelection {

protected void initUI() {
final DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
fillTree(root, 5, "Some tree label");
final DefaultTreeModel model = new DefaultTreeModel(root);
final JTree tree = new JTree(model);
tree.addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
boolean inside = false;
TreePath path = tree.getPathForLocation(e.getX(), e.getY());
if (path != null) {
Rectangle pathBounds = tree.getPathBounds(path);
inside = pathBounds.contains(e.getPoint());
}
if (inside) {
tree.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
} else {
tree.setCursor(Cursor.getDefaultCursor());
}
}
});
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(tree));
f.setSize(400, 600);
f.setLocationRelativeTo(null);
f.setVisible(true);
}

private void fillTree(DefaultMutableTreeNode parent, int level, String label) {
for (int i = 0; i < 5; i++) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(label + " " + i);
parent.add(node);
if (level > 0) {
fillTree(node, level - 1, label);
}
}
}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
new TestTreeSelection().initUI();
}
});
}

}

关于java - 想要在 JTree 列出的元素上移动鼠标时更改光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14522221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com