JTree: Set custom open/closed icons for individual groups

前端 未结 2 1936
礼貌的吻别
礼貌的吻别 2020-12-01 23:01
  1. I know how to set custom leaf icons in JTree
  2. I know how to set custom closed/open icons for all group nodes

But I can not set custom open/close

2条回答
  •  北海茫月
    2020-12-01 23:50

    In your TreeCellRenderer, you can use setOpenIcon() and setClosedIcon() as required in conjunction with the defined parameters and predicates related to your model. Given a tree having the default JTree model, the TreeRenderer below will use the closed and open icons for the sports node:

    iamge

    private static class TreeRenderer extends DefaultTreeCellRenderer {
    
        private static final Icon closed =
            (Icon) UIManager.get("InternalFrame.maximizeIcon");
        private static final Icon open =
            (Icon) UIManager.get("InternalFrame.minimizeIcon");
    
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
            String s = node.getUserObject().toString();
            if ("sports".equals(s)) {
                setOpenIcon(open);
                setClosedIcon(closed);
            } else {
                setOpenIcon(getDefaultOpenIcon());
                setClosedIcon(getDefaultClosedIcon());
            }
            super.getTreeCellRendererComponent(
                tree, value, sel, exp, leaf, row, hasFocus);
            return this;
        }
    }
    

    See also this related example.

提交回复
热议问题