gpt4 book ai didi

java - JTree 通过鼠标事件选择节点

转载 作者:行者123 更新时间:2023-12-01 11:57:21 25 4
gpt4 key购买 nike

我正在尝试跟踪用户在 JTree 上使用鼠标监听器单击的节点。单击事件有效,但我无法选择树中的节点。

public FileTreeController(JTree t) {
this.myTree = t;
this.myTree.setCellRenderer(new FileTreeCellRenderer());

this.myTree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
doMouseClicked(me);
}
});

this.renderTree();
}

private void doMouseClicked(MouseEvent me) {
int selRow = this.myTree.getRowForLocation(me.getX(), me.getY());
TreePath selPath = this.myTree.getPathForLocation(me.getX(), me.getY());
if (selRow != -1) {
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) ((DefaultMutableTreeNode) selPath.getLastPathComponent());
TreeNode selectedTreeNode = (TreeNode) selectedNode.getUserObject();

//Doesn't work
this.myTree.getSelectionModel().addSelectionPath(selPath);
this.myTree.setSelectionRow(selRow);

if (SwingUtilities.isLeftMouseButton(me)) {
if (me.getClickCount() == 1) {

} else if (me.getClickCount() == 2) {
System.out.println(selectedTreeNode.getText());
}
} else if (SwingUtilities.isRightMouseButton(me)) {
if (me.getClickCount() == 1) {
System.out.println("Right");
}
}
}
}

这是我自己的类,它在 JTree 中表示并包含所有信息。

class TreeNode {
private String text = "";
private String icon = "";
private String path = "";

public TreeNode(String txt, String iconpath, String path) {
this.text = txt;
this.icon = iconpath;
this.path = path;
}

public TreeNode(String txt, IconType iconpath, String path) {
this.text = txt;
this.icon = iconpath.toString();
this.path = path;
}

public String getText() {
return this.text;
}

public String getIcon() {
return Validator.validatePath(this.icon);
}

public String getPath(){
return Validator.validatePath(this.path);
}
}

class FileTreeCellRenderer implements TreeCellRenderer {
private JLabel label;

FileTreeCellRenderer() {
label = new JLabel();
}

public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
Object o = ((DefaultMutableTreeNode) value).getUserObject();
if (o instanceof TreeNode) {
TreeNode treeNode = (TreeNode) o;
label.setIcon(new ImageIcon(treeNode.getIcon()));
label.setText(treeNode.getText());
} else {
label.setIcon(null);
label.setText("" + value);
}
return label;
}
}

最佳答案

似乎您看不到您的选择,因为您没有在 FileTreeCellRenderer 中实现颜色更改:

  1. 像下面这样更改构造函数:

    FileTreeCellRenderer() {
    label = new JLabel();
    label.setOpaque(true);
    }
  2. getTreeCellRendererComponent() 中更改颜色,如下所示:

    label.setBackground(selected ? Color.BLUE : tree.getBackground());
    label.setForeground(selected ? Color.WHITE : tree.getForeground());

关于java - JTree 通过鼠标事件选择节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28340715/

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