Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package test;
import com.intellij.icons.AllIcons;
import com.intellij.ide.projectView.PresentationData;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.startup.StartupActivity;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.tree.AsyncTreeModel;
import com.intellij.ui.tree.StructureTreeModel;
import com.intellij.ui.treeStructure.SimpleNode;
import com.intellij.ui.treeStructure.SimpleTreeStructure;
import com.intellij.ui.treeStructure.Tree;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
class AsyncTreeModelTest implements Disposable, StartupActivity {
private TestSimpleNode root = new TestSimpleNode("First child",
new TestSimpleNode("Second child 1", new TestSimpleNode("Third child")),
new TestSimpleNode("Second child 2", new TestSimpleNode("Third child")));
@Override
public void runActivity(@NotNull Project project) {
var treeStructure = new TestSimpleTreeStructure();
var treeModel = new StructureTreeModel(treeStructure, this);
var mutableNode = new DefaultMutableTreeNode();
var tree = new Tree(mutableNode);
var model = new AsyncTreeModel(treeModel, this);
tree.setModel(model);
tree.setRootVisible(false);
var component = new JPanel(new BorderLayout());
component.add(new JBScrollPane(tree), "Center");
JFrame jFrame = new JFrame();
jFrame.setPreferredSize(new Dimension(500, 500));
jFrame.add(component);
jFrame.pack();
jFrame.setVisible(true);
new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException ignored) {
}
root.addChild(new TestSimpleNode("Inserted child"));
treeModel.invalidate();
}).start();
}
@Override
public void dispose() {
}
public class TestSimpleNode extends SimpleNode {
private final String text;
private final List<SimpleNode> children;
public TestSimpleNode(String text, SimpleNode... children) {
this.text = text;
this.children = new ArrayList<>(List.of(children));
}
public void addChild(SimpleNode child) {
this.children.add(child);
}
@Override
protected void update(@NotNull PresentationData presentation) {
presentation.addText(text, SimpleTextAttributes.GRAYED_ATTRIBUTES);
presentation.setIcon(AllIcons.Nodes.Method);
}
@NotNull
@Override
public SimpleNode[] getChildren() {
return children.toArray(new SimpleNode[0]);
}
}
public class TestSimpleTreeStructure extends SimpleTreeStructure {
@NotNull
@Override
public Object getRootElement() {
return new TestSimpleNode("Root", root);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment