0

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 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?

1 Answer 1

1

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;
      }
    }   
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Are you a bot? ... tht was reall fast!
Its working but again when I switch from one tree to another for selecting, I need to double click the node before it gets highlighted. (Although clicking the node for the first time does trigger the action I am looking for, its juts that the node gets highlighted only after the second click). Is this the expected course your piece of code should take?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.