nt.UI/src/nt/UI/display/ObjTreeCellRenderer.java

70 lines
2.2 KiB
Java

package nt.UI.display;
import java.awt.Color;
import java.awt.Component;
import java.net.URL;
import java.util.HashMap;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellRenderer;
import nt.UI.util.IconResizer;
import nt.UI.util.Icons;
public class ObjTreeCellRenderer implements TreeCellRenderer{
private HashMap<Class<?>, Icon> mappedIcons = new HashMap<>();
private Color bgSelect = new Color(Integer.decode("#5e87ed"));
public ObjTreeCellRenderer() {
putIcon(String.class, Icons.STRING_SYMBOL_URL);
putIcon(Long.class, Icons.NUMBER_SYMBOL_URL);
putIcon(Integer.class, Icons.NUMBER_SYMBOL_URL);
putIcon(Short.class, Icons.NUMBER_SYMBOL_URL);
putIcon(Float.class, Icons.NUMBER_SYMBOL_URL);
putIcon(Double.class, Icons.NUMBER_SYMBOL_URL);
putIcon(Object.class, Icons.OBJECT_SYMBOL_URL);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
if(value == null) {
return null;
}
Class<?> valClass = value.getClass();
valClass = valClass==DefaultMutableTreeNode.class? ((DefaultMutableTreeNode)value).getUserObject().getClass() : valClass;
Icon icon = leaf?mappedIcons.get(valClass) : expanded? new ImageIcon(Icons.DIRECTORY_SYMBOL_URL) : new ImageIcon(Icons.SUBMODULE_SYMBOL_URL);
icon = icon==null? new ImageIcon(Icons.FILE_SYMBOL_URL): icon;
int fHeight = tree.getFontMetrics(tree.getFont()).getHeight() - 4;
int iWidth = (int)((fHeight / (float)icon.getIconHeight()) * icon.getIconWidth());
icon = IconResizer.resizeIcon(icon, iWidth, fHeight);
JLabel label = new JLabel(value.toString());
label.setIconTextGap(10);
label.setFont(tree.getFont());
label.setOpaque(true);
label.setIcon(icon);
Color bg = selected? bgSelect : tree.getBackground();
Color fg = tree.getForeground();
label.setBackground(bg);
label.setForeground(fg);
return label;
}
public void putIcon(Class<?> clazz, Icon icon) {
this.mappedIcons.put(clazz, icon);
}
public void putIcon(Class<?> clazz, URL url) {
putIcon(clazz, new ImageIcon(url));
}
}