changing how Nimbus LaF handles JTree node highlighting

纵饮孤独 提交于 2019-12-04 04:16:10

Edit

The "Tree.selectionBackground" key is what controls the highlight on the JTree - it's done on the tree level, not on the TreeCellRenderer level (which is why it's a little confusing to manage). This code will get you a Tree where you can control the highlighting:

private JTree getJTree() {

    JTree jTree = new JTree();
    jTree.setOpaque(true);
    jTree.setBackground(Color.white);
    UIDefaults paneDefaults = new UIDefaults();
    paneDefaults.put("Tree.selectionBackground",null);

    JTextPane pane = new JTextPane();
    jTree.putClientProperty("Nimbus.Overrides",paneDefaults);
    jTree.putClientProperty("Nimbus.Overrides.InheritDefaults",false);

    jTree.setCellRenderer( new LocalRenderer() );
    return jTree;
}

And here's an example of changing the highlighting to Red. Please note that the Icon's background will be highlighted too - this is the default behavior for non-nimbus L&F too. If you don't want the icon to be highlighted, you're going to have to use something fancier than the default JLabel to render the TreeCell:

    public Component getTreeCellRendererComponent( JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasfocus ) {
        DefaultTreeCellRenderer result = (DefaultTreeCellRenderer)super.getTreeCellRendererComponent( tree, value, sel, expanded, leaf, row, hasfocus );
        result.setOpaque(true);
            if( true ) {
                result.setFont( new JLabel().getFont() );
                Icon icon = UIManager.getIcon("FileView.floppyDriveIcon");
                result.setIcon( icon );
            }
            if(sel){
                result.setBackground(Color.red);
            } else{
                result.setBackground(Color.white);
            }
        return(result);
    }

Original Answer

One of the easiest ways to fix this is to set the selected background color to transparent. The problem is that it's trying to paint the background of the label - which doesn't have the cool Nimbus painter used by the JTree's selection. So add this line to getTreeCellRendererComponent method:

result.setBackgroundSelectionColor(new Color(0,0,0,0));

Another option is to use the nimbus painter for the background of the TreeCellRenderer - but that seems like overkill in this situation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!