开发者

Java Issue with Tree Selection

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?

After Editing:

Now if I only do

     if ( tree == tree1 ){

        if(!tree2.isSelectionEmpty()){

            tree2.clearSelection();

        }

    } else {

        if(!tree1.isSelectionEmpty()){

            tree1.clearSelection();
        }

    }

The first tim开发者_JAVA百科e 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 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.

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;
      }
    }   
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜