How to change style (color, font) of a single JTree node

狂风中的少年 提交于 2019-12-18 08:28:08

问题


I have two JTree in two panels in a JFrame. I want to change the style(color and font) of nodes on drag and drop from one tree to the other.Please provide me a way to change the color of a JTree node permanently.


回答1:


To start, you will need to have a data object that can handle style and color. You could subclass DefaultMutableTreeNode and add these data items with getts and setters

Then you'd need to create a custom TreeCellRenderer. I recommend extending DefaultTreeCellRenderer, and in the overridden handler, checking for your custom class, and modifying the JLabel output to use the Font and Color if these values are set




回答2:


Create your own CellRenderer. To give the appropriate behaviour to your MyTreeCellRenderer, you will have to extend DefaultTreecellRenderer and override the getTreeCellRendererComponent method.

public class MyTreeCellRenderer extends DefaultTreeCellRenderer {

    @Override
    public Component getTreeCellRendererComponent(JTree tree, Object value,
            boolean sel, boolean exp, boolean leaf, int row, boolean hasFocus) {
        super.getTreeCellRendererComponent(tree, value, sel, exp, leaf, row, hasFocus);

        // Assuming you have a tree of Strings
        String node = (String) ((DefaultMutableTreeNode) value).getUserObject();

        // If the node is a leaf and ends with "xxx"
        if (leaf && node.endsWith("xxx")) {
            // Paint the node in blue
            setForeground(new Color(13, 57 ,115));
        }

        return this;
    }
}

Finally, say your tree is called myTree, set your CellRenderer to it:

myTree.setCellRenderer(new MyTreeCellRenderer());


来源:https://stackoverflow.com/questions/10111849/how-to-change-style-color-font-of-a-single-jtree-node

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