Plugin JTree with custom TreeCellRenderer
已回答
Hello,
I have a JTree component with three levels (server, folder, file). I use custom TreeCellRenderer to style icons for each level. There is an issue when IDEA theme change triggered (dark to light / light to dark) and all UI text elements change color, the color of JTree node JLabels text isn't changed.
My custom TreeCellRenderer:
public class CustomTreeCellRenderer implements javax.swing.tree.TreeCellRenderer {
private JLabel label;
public CustomTreeCellRenderer() {
label = new JLabel();
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
if (value instanceof TreeNodeHost) {
TreeNodeHost host = (TreeNodeHost) value;
label.setIcon(host.getIcon());
label.setText(host.configuration.getFullHostString());
} else if (value instanceof TreeNodeFolder) {
TreeNodeFolder folder = (TreeNodeFolder) value;
label.setIcon(folder.getIcon());
label.setText(folder.getUserObject().toString());
} else if (value instanceof TreeNodeFile) {
TreeNodeFile file = (TreeNodeFile) value;
label.setIcon(file.getIcon());
label.setText(file.getUserObject().toString());
}
return label;
}
}
where TreeNodeHost, TreeNodeFolder, TreeNodeFile are custom Tree Nodes objects (extend DefaultMutableTreeNode).
How would one go about changing label color on theme change?
请先登录再写评论。
Please make your renderer extends javax.swing.tree.DefaultTreeCellRenderer like this:
Thank you Vassiliy, now my tree change color together with theme change.
Hello Vassiliy, I am also facing the exact same issue. I tried the DefaultTreeCellRenderer but unable to fix this theme change issue. Can you please suggest If there is anything I need to change in the below code:
class Renderer extends DefaultTreeCellRenderer {
private JLabel label;
public Renderer() {
this.label = new JLabel();
}
@Override
public Component getTreeCellRendererComponent(
final JTree tree,
final Object value,
final boolean sel,
final boolean expanded,
final boolean leaf,
final int row,
final boolean hasFocus) {
label =
(JLabel)
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
if (node.getUserObject() instanceof VseResponse) {
final VseResponse response = (VseResponse) node.getUserObject();
label.setText(response.getName());
label.setIcon(VSEManagerIcons.VSE_PLUGIN_ICON);
}
if (node.getUserObject() instanceof VseVirtualServiceResponse) {
final VseVirtualServiceResponse response = (VseVirtualServiceResponse) node.getUserObject();
label.setText(response.getName());
label.setIcon(VSEConstants.VSE_STATUS[Integer.parseInt(response.getStatus())]);
}
return label;
}
}