简体   繁体   中英

JTree disable highlight effect on certain nodes

I have a Jtree and I need to remove the highlight effect on certain node.

So, now I have this for alla nodes

在此处输入图片说明

and I would like have this on certain node:

在此处输入图片说明

How can I achieve this ? Thanks

Could you not maybe use something like this ? Unsure of practicality and not tested it

tree.addMouseListener (new MouseAdapter (){

        public void mousePressed ( MouseEvent e ){

           // Check for right click
           if (SwingUtilities.isRightMouseButton(e)){

                  int selection[] = tree.getSelectionRows();

                  for(int i=0; i< selection.size; i++){

                     tree.removeSelectionInterval(selection[i], selection[i]);
                  }
           }
}

- First: you need to set an object (with your own property) to the node with the following method:

Group aGroup = new Group(); //Obviously use your correct constructor 
DefaultMutableTreeNode node = new DefaultMutableTreeNode(yourObject);

Remember to implement toString method in Group class

- Second: Create a new class that extends DefaultTreeCellRenderer and override getTreeCellRendererComponent like this:

public class MyRenderer extends DefaultTreeCellRenderer {

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

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;

            if(node.getUserObject().getYourProperty()){
                 setTextNonSelectionColor(Color.BLACK);
                 setBackgroundSelectionColor(Color.BLUE);
                 setTextSelectionColor(Color.WHITE);
                 setBorderSelectionColor(Color.WHITE);
            }
           else{
                 setTextNonSelectionColor(Color.LIGHT_GRAY);
                 setBackgroundSelectionColor(Color.RED);
                 setTextSelectionColor(Color.WHITE);
                 setBorderSelectionColor(Color.WHITE);
           }

            super.getTreeCellRendererComponent(
                tree, value, sel, exp, leaf, row, hasFocus);
            return this;
        }
}

-Third : set your renderer to tree:

yourTree.setCellRenderer(new MyRenderer());

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