gpt4 book ai didi

Java 树选择问题

转载 作者:行者123 更新时间:2023-12-01 16:09:36 25 4
gpt4 key购买 nike

在我的程序中,我有 2 个 JTree,并且两者都有一个通用的 treeselection 监听器。当我在第一棵树中选择一个节点,然后立即在第二棵树中选择一个节点时,就会出现问题。现在,如果我返回并在第一棵树中选择最初选择的相同节点,则不会发生任何情况。我该如何解决这个问题?有没有办法在 valueChanged 事件处理程序末尾取消选择节点?

编辑后:

现在只要我这样做

     if ( tree == tree1 ){

if(!tree2.isSelectionEmpty()){

tree2.clearSelection();

}

} else {

if(!tree1.isSelectionEmpty()){

tree1.clearSelection();
}

}

我第一次选择树时效果很好。但是第二次,如果我从不同的树中选择,监听器会被触发两次,我必须双击才能选择它。知道为什么吗?

最佳答案

Swing 在失去焦点时不会清除 JTree(或 JTable、JList 等)的选择。您需要自己定义这个逻辑。因此,在您的示例中,返回并选择第一棵树中的节点没有任何效果,因为它已被选择。

下面是一个示例 TreeSelectionListener 实现,当对一个 JTree 进行选择时,它将清除对另一个 JTree 的选择。

public static class SelectionMaintainer implements TreeSelectionListener {
private final JTree tree1;
private final JTree tree2;

private boolean changing;

public SelectionMaintainer(JTree tree1, JTree tree2) {
this.tree1 = tree1;
this.tree2 = tree2;
}

public valueChanged(TreeSelectionEvent e) {
// Use boolean flag to guard against infinite loop caused by performing
// a selection change in this method (resulting in another selection
// event being fired).
if (!changing) {
changing = true;
try {
if (e.getSource == tree1) {
tree2.clearSelection();
} else {
tree1.clearSelection();
}
} finally {
changing = false;
}
}
}
}

关于Java 树选择问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1754521/

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