Java如何更改JTree中选定节点的颜色?

本示例说明如何更改JTree组件的所选节点的颜色。它显示了如何设置节点背景色,字体颜色和选定的节点边框颜色。

为此,您需要DefaultTreeCellRenderer从JTree实例获取对象并修改节点的选择颜色。

package org.nhooo.example.swing;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import java.awt.*;

public class JTreeTextSelectionColorDemo extends JFrame {
    public JTreeTextSelectionColorDemo() throws HeadlessException {
        initializeUI();
    }

    private void initializeUI() {
        setSize(150, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Department");
        DefaultMutableTreeNode book = new DefaultMutableTreeNode("Books");
        DefaultMutableTreeNode fiction = new DefaultMutableTreeNode("Fictions");
        DefaultMutableTreeNode science = new DefaultMutableTreeNode("Sciences");
        DefaultMutableTreeNode text = new DefaultMutableTreeNode("Text Books");
        DefaultMutableTreeNode children = new DefaultMutableTreeNode("Children");

        root.add(book);
        book.add(fiction);
        book.add(science);
        book.add(text);
        book.add(children);

        JTree tree = new JTree(root);

        // 获取JTree的DefaultTreeCellRenderer实例
        //零件。然后我们自定义选择的颜色
        // 节点使用蓝色背景,白色字体颜色和黑色
        // 边境。
        DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
        renderer.setTextSelectionColor(Color.white);
        renderer.setBackgroundSelectionColor(Color.blue);
        renderer.setBorderSelectionColor(Color.black);

        JScrollPane pane = new JScrollPane(tree);
        pane.setPreferredSize(new Dimension(150, 300));

        getContentPane().add(pane);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new JTreeTextSelectionColorDemo().setVisible(true);
            }
        });
    }
}