Java Issue with Tree Selection

坚强是说给别人听的谎言 提交于 2019-12-11 15:49:30

问题


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:


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


来源:https://stackoverflow.com/questions/1754521/java-issue-with-tree-selection

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!