树选择的Java问题 [英] Java Issue with Tree Selection

查看:110
本文介绍了树选择的Java问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my program, I have 2 JTrees and there is a common treeselection listener for both. The problem happens when I select a node in the first tree and then immediately select a node in the second tree.Now if I were to go back and select the same node in the first tree that was initially selected, nothing happens. How do I solve this? Is there a way to unselect a node at the end of a valueChanged event handler?

编辑后:

现在,如果我只做

     if ( tree == tree1 ){

        if(!tree2.isSelectionEmpty()){

            tree2.clearSelection();

        }

    } else {

        if(!tree1.isSelectionEmpty()){

            tree1.clearSelection();
        }

    }

我第一次选择树时效果很好.但是第二次,如果我从另一棵树中进行选择,则监听器将被触发两次,并且我必须双击以将其选中.有什么线索吗?

The first time I select the tree it works fine. But the second time if I select from a different tree, the listener gets fired twice and I have to double click to select it. Any clue why?

推荐答案

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

Swing will not clear the selection of a JTree (or JTable, JList, etc) when it loses focus. You need to define this logic yourself. Hence in your example, going back and selecting the node in the first tree is having no effect because it is already selected.

这是示例TreeSelectionListener的实现,当对另一个JTree进行选择时,该实现将清除对另一个JTree的选择.

Here is an example TreeSelectionListener implementation that will clear the selection of one JTree when a selection is made on the other one.

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问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆