Skip to content

Instantly share code, notes, and snippets.

@aterai
Created June 14, 2016 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aterai/86c078f5c5bac2adb5241048fda87c0c to your computer and use it in GitHub Desktop.
Save aterai/86c078f5c5bac2adb5241048fda87c0c to your computer and use it in GitHub Desktop.
import java.awt.*;
import java.awt.image.ImageObserver;
import java.util.Objects;
import javax.swing.*;
import javax.swing.tree.*;
public class AnimatedTreeNodeTest {
public JComponent makeUI() {
ImageIcon icon = new ImageIcon(getClass().getResource(
"restore_to_background_color.gif"));
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
DefaultMutableTreeNode s0 = new DefaultMutableTreeNode(new NodeObject("a"));
DefaultMutableTreeNode s1 = new DefaultMutableTreeNode(new NodeObject("b", icon));
root.add(s0);
root.add(s1);
JTree tree = new JTree(new DefaultTreeModel(root));
tree.setCellRenderer(new DefaultTreeCellRenderer() {
@Override public Component getTreeCellRendererComponent(
JTree tree, Object value, boolean selected, boolean expanded, boolean leaf,
int row, boolean hasFocus) {
JLabel l = (JLabel) super.getTreeCellRendererComponent(
tree, value, selected, expanded, leaf, row, hasFocus);
if (value instanceof MutableTreeNode
&& ((DefaultMutableTreeNode) value).getUserObject() instanceof NodeObject) {
NodeObject uo = (NodeObject) ((DefaultMutableTreeNode) value).getUserObject();
l.setText(Objects.toString(uo.title, ""));
l.setIcon(uo.icon);
} else {
l.setText(Objects.toString(value, ""));
l.setIcon(null);
}
return l;
}
});
TreePath path = new TreePath(s1.getPath());
//Wastefulness: icon.setImageObserver((ImageObserver) tree);
icon.setImageObserver(new ImageObserver() {
@Override public boolean imageUpdate(
Image img, int infoflags, int x, int y, int w, int h) {
if (!tree.isShowing()) {
return false;
}
Rectangle cellRect = tree.getPathBounds(path);
if ((infoflags & (FRAMEBITS | ALLBITS)) != 0 && Objects.nonNull(cellRect)) {
tree.repaint(cellRect);
}
return (infoflags & (ALLBITS | ABORT)) == 0;
}
});
return new JScrollPane(tree);
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new AnimatedTreeNodeTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
class NodeObject {
public final Icon icon;
public final String title;
protected NodeObject(String title) {
this(title, null);
}
protected NodeObject(String title, Icon icon) {
this.title = title;
this.icon = icon;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment