Search code examples
javaswingjtreedeselect

Deselect a JTree


I have a JPanel containing 8 different JTrees, each one of them in a JScrollPane.

When I click on a tree node, it got always selected even if I select a different tree. So the situation could be the following:

enter image description here

My simple goal is to deselect a tree when I click on another one.

I already solved this problem but not in an efficient and elegant way, doing this for each tree:

JScrollPane scrollPane = new JScrollPane(treeONE);
    treeONE.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            treeTWO.clearSelection();
            treeTHREEC.clearSelection();
            treeFOUR.clearSelection();
            treeFIVE.clearSelection();
            treeSIX.clearSelection();
            treeSEVEN.clearSelection();
            treeEIGHT.clearSelection();
        }
    });
    add(scrollPane);

Is there a better way to code this?


Solution

  • Define an array containing all your trees:

    JTree[] allTrees = {
        treeONE, treeTWO, treeTHREE, treeFOUR, treeFIVE, treeSIX, treeSEVEN, treeEIGHT
    };
    

    Then you can use the same MouseListener instance for all your trees:

    MouseListener mouseListenerForAllTrees = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            // deselect all trees except the one which fired the event
            for (JTree tree : allTrees) {
                if (tree != e.getSource())
                    tree.clearSelection();
            }
        }
    };
    for (JTree tree : allTrees) {
        tree.addMouseListener(mouseListenerForAllTrees);
    }