diff --git a/platform/platform-impl/src/com/intellij/ui/tree/RestoreSelectionListener.java b/platform/platform-impl/src/com/intellij/ui/tree/RestoreSelectionListener.java index 28a4889bcdf5..bdd1ca3c9646 100644 --- a/platform/platform-impl/src/com/intellij/ui/tree/RestoreSelectionListener.java +++ b/platform/platform-impl/src/com/intellij/ui/tree/RestoreSelectionListener.java @@ -1,6 +1,4 @@ -/* - * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. - */ +// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui.tree; import org.jetbrains.annotations.NotNull; @@ -11,6 +9,7 @@ import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreePath; import static com.intellij.util.ui.tree.TreeUtil.visitVisibleRows; +import static java.awt.EventQueue.invokeLater; /** * Temporary solution to restore selection in a tree. @@ -26,21 +25,24 @@ public final class RestoreSelectionListener implements TreeSelectionListener { if (source instanceof JTree) { JTree tree = (JTree)source; if (tree.getSelectionModel().isSelectionEmpty()) { - // restore a path selection only if nothing is selected now - Reference reference = new Reference<>(); - TreeVisitor visitor = new TreeVisitor.ByTreePath(path, o -> o) { - @NotNull - @Override - protected Action visit(@NotNull TreePath path, Object component) { - Action action = super.visit(path, component); - if (action == Action.CONTINUE) reference.set(path); - return action; + invokeLater(() -> { + // restore selection later, because nodes are removed before they are inserted + if (tree.getSelectionModel().isSelectionEmpty()) { + // restore a path selection only if nothing is selected now + Reference reference = new Reference<>(); + TreeVisitor visitor = new TreeVisitor.ByTreePath(path, o -> o) { + @NotNull + @Override + protected Action visit(@NotNull TreePath path, Object component) { + Action action = super.visit(path, component); + if (action == Action.CONTINUE || action == Action.INTERRUPT) reference.set(path); + return action; + } + }; + visitVisibleRows(tree, visitor); + tree.setSelectionPath(reference.get()); } - }; - if (visitVisibleRows(tree, visitor) == null) { - // select last visible parent only if the given path is not visible anymore - tree.setSelectionPath(reference.get()); - } + }); } } }