简体   繁体   中英

JTree Custom TreeCellRenderer / Selected node-specific color

i am trying to set a different background color for different nodes of a JTree . The user can right click on a node, push a button and choose a color from a JColorChooser . I made a custom treecellrenderer(Chromatizer()) and overriden the method .getTreeCellRendererComponent() in order to set the BackgroundNonSelectionColor with the chosen color. What happens is that even though this happens beggining from current selection , it expands if selections changes . Is there any way to change the color of just the selected node?

      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();

             }
        });
    }    


}

And the Custom renderer

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;





 }  

};

Images(couldn't upload due to being a new member ! : )

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

maybe you can use this

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM