0

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

编辑后:

现在如果我只做

     if ( tree == tree1 ){

        if(!tree2.isSelectionEmpty()){

            tree2.clearSelection();

        }

    } else {

        if(!tree1.isSelectionEmpty()){

            tree1.clearSelection();
        }

    }

我第一次选择树时它工作正常。但是第二次如果我从不同的树中选择,监听器会被触发两次,我必须双击才能选择它。任何线索为什么?

4

1 回答 1

1

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

这是一个示例TreeSelectionListener实现,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;
      }
    }   
  }
}
于 2009-11-18T08:50:26.387 回答