JTree set background of node to non-opaque

后端 未结 2 392
自闭症患者
自闭症患者 2021-01-11 22:35

Please have a look at the SSCCE. How can I make the non-selected tree nodes\' background transparent. At the moment the background of non-selected nodes is white. My cell re

相关标签:
2条回答
  • 2021-01-11 23:10

    You should override getBackgroundNonSelectionColor,getBackgroundSelectionColor and getBackground of DefaultTreeCellRenderer and return appropriate values like so:

    public class MyCellRenderer extends DefaultTreeCellRenderer {
    
        @Override
        public Color getBackgroundNonSelectionColor() {
            return (null);
        }
    
        @Override
        public Color getBackgroundSelectionColor() {
            return Color.GREEN;
        }
    
        @Override
        public Color getBackground() {
            return (null);
        }
    
        @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) {
            final Component ret = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
    
            final DefaultMutableTreeNode node = ((DefaultMutableTreeNode) (value));
            this.setText(value.toString());
            return ret;
        }
    }
    

    which will produce:

    enter image description here

    Other suggestions:

    • Create and manipulate Swing components on Event Dispatch Thread.
    • Dont extend JFrame unnecessarily rather create an instance and use that.
    • Dont call setSize on JFrame rather use a correct LayoutManager and/or override getPreferredSize() and call pack() on JFrame before setting it visible but after adding all components.
    • Remember to call JFrame#setDefaultCloseOperation with either DISPOSE_ON_CLOSE or EXIT_ON_CLOSE (DISPOSE_XXX is usually preferred unless using Timers as this will allow main(String[] args) to continue its execution after Gui has been closed).
    0 讨论(0)
  • 2021-01-11 23:28

    To avoid background refilling, just put UIManager.put("Tree.rendererFillBackground", false); before new SimpleTree(); or after super("Creating a Simple JTree");.

    0 讨论(0)
提交回复
热议问题