JTree自定义TreeCellRenderer /特定于节点的颜色

时间:2015-07-16 13:59:59

标签: swing colors jtree jcolorchooser treecellrenderer

我正在尝试为JTree的不同节点设置不同的背景颜色。用户可以右键单击节点,按下按钮并从JColorChooser中选择颜色。我创建了一个自定义的treecellrenderer(Chromatizer())并重写方法.getTreeCellRendererComponent(),以便使用所选颜色设置BackgroundNonSelectionColor。会发生的是,即使这种情况发生在当前选择之外,如果选择发生变化,它也会扩展。有没有办法改变所选节点的颜色?

      public class TreeExample extends JFrame
    {
        private JTree tree;
        private JButton btn; 

        public TreeExample()
        {
btn = new JButton ("Choose a color");
        Chromatizer chroma = new Chromatizer();

DefaultMutableTreeNode root = new DefaultMutableTreeNode("Letters");
         DefaultMutableTreeNode parent1 = new DefaultMutableTreeNode("uppercase");
         DefaultMutableTreeNode parent2 = new DefaultMutableTreeNode("lowercase");
         DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("A");
         DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("B");
         DefaultMutableTreeNode child3 = new DefaultMutableTreeNode("C");
         DefaultMutableTreeNode child4 = new DefaultMutableTreeNode("a");
         DefaultMutableTreeNode child5 = new DefaultMutableTreeNode("b");
         DefaultMutableTreeNode child6 = new DefaultMutableTreeNode("c");

         root.add(parent1);
         root.add(parent2);

         parent1.add(child1);
         parent1.add(child2);
         parent1.add(child3);

         parent2.add(child4);
         parent2.add(child5);
         parent2.add(child6);

         tree = new JTree(root);


        ImageIcon imageIcon = new ImageIcon(TreeExample.class.getResource("./leaf.jpg"));
        chroma.setLeafIcon(imageIcon);

         tree.setCellRenderer(chroma);  
tree.setShowsRootHandles(true);
        tree.setRootVisible(false);


        add(new JScrollPane(tree)

        );

        /*

        Start of btn

        */     




        btn.addActionListener(
        new ActionListener(){
            private DefaultMutableTreeNode dmt;



            @Override
            public void actionPerformed(ActionEvent event){




                  dmt = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();




                    Color clr = null;
                   clr =JColorChooser.showDialog(null, "Επιλογή χρώματος", clr); 

                    chroma.getTreeCellRendererComponent(tree, dmt, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled, ERROR, rootPaneCheckingEnabled, clr);


 (             (DefaultTreeModel) tree.getModel()).nodeChanged(dmt);



                           }
       );


        /*end of btn */


        /*right mouse click menu*/
        tree.addMouseListener(new MouseAdapter ()
    {
        public void mousePressed(MouseEvent e)
        {
            if ( SwingUtilities.isRightMouseButton ( e ) )
            {
                int row = tree.getClosestRowForLocation(e.getX(), e.getY());
                tree.setSelectionRow(row);
                TreePath path = tree.getPathForLocation ( e.getX (), e.getY () );
                Rectangle pathBounds = tree.getUI ().getPathBounds ( tree, path );
                if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) )
                {
                    JPopupMenu menu = new JPopupMenu ();
                    menu.add (btn) ;
                    menu.show ( tree, pathBounds.x, pathBounds.y + pathBounds.height );

                }

            }

         }

    }  );

        /*end of menu*/

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("JTree Example");        
        this.setSize(200, 200);
        this.setVisible(true); 

    }




    public static void main(String[] args)
    {


        SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                new TreeExample();

             }
        });
    }    


}

自定义渲染器

public class  Chromatizer extends DefaultTreeCellRenderer {

public Component getTreeCellRendererComponent(
                    JTree tree,
                    Object value,
                    boolean sel,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus,
                    Color color) 
{


    super.getTreeCellRendererComponent(
                    tree, value, sel,
                    expanded, leaf, row,
                    hasFocus);




   DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;

      if(node.getParent() != null){

             super.setBackgroundNonSelectionColor(color);
             super.setBackgroundSelectionColor(color);

      } 

    return this;





 }  

};

图片(由于是新会员而无法上传!)

First Screen[1]  http://i.stack.imgur.com/lNrKA.jpg
After right-clicking and pushing button "Choose a color"[2] http://i.stack.imgur.com/XICRp.jpg
Result after clicking ok[3]
 http://i.stack.imgur.com/l48ft.jpg
If I left-click there(arrow) then tree nodes are filled with color[4]
 http://i.stack.imgur.com/1CEkS.jpg

1 个答案:

答案 0 :(得分:0)

也许你可以使用这个

DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();
//do something with one of this parameter
//tree, value, selected, expanded, leaf, row, hasFocus


Component returnValue = defaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
return returnValue;