JTree Nimbus selection treeNode

I made a jtree with a custom TreeCellRenderer. The leaf nodes are a jpanel with a checkbox in and JPanel. The problem now is that when you select a tree node, there is a selection color box beside the jpanel.
Here is a sscce:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
public class Users {
    private static JFrame frame;
    private static JPanel usersPanel;
    private JTree usersTree;
    public Users(){
        usersPanel = new JPanel();
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Gebruikers");
        DefaultMutableTreeNode willie = new DefaultMutableTreeNode("Willie");
        DefaultMutableTreeNode Anna = new DefaultMutableTreeNode("Anna");
        rootNode.add(willie);
        rootNode.add(Anna);
        usersTree = new JTree(rootNode);
        myTreeWithCheckBoxRenderer renderer = new myTreeWithCheckBoxRenderer();
        usersTree.setCellRenderer(renderer);
        usersTree.setRootVisible(true);
        usersTree.setEditable(false);
        usersTree.setOpaque(false);
        usersPanel.add(usersTree);
    class myTreeWithCheckBoxRenderer extends DefaultTreeCellRenderer {
        DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
        JPanel panel;
        JCheckBox checkBox;
        JLabel label;
        public myTreeWithCheckBoxRenderer() {
            checkBox = new JCheckBox();
            label = new JLabel("Gebruikers");
            panel = new JPanel(new BorderLayout());
            panel.add(checkBox, BorderLayout.WEST);
            panel.add(label, BorderLayout.EAST);
            panel.setBackground(Color.red);
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            Component returnValue;
            if(!leaf){
                renderer.setBackgroundSelectionColor(null);
                renderer.setText("Gebruikers");
                returnValue = renderer;
            else{
                if(hasFocus){
                    panel.setBackground(Color.blue);
                returnValue = panel;
            return returnValue;
    private static void createAndShowGUI(){
        new Users();
        frame = new JFrame("Tree");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(usersPanel);
        frame.pack();
        frame.setPreferredSize(new Dimension(800, 600));
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
     public static void main (String[] args){
        try {
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
        } catch (UnsupportedLookAndFeelException e) {
            // handle exception
        } catch (ClassNotFoundException e) {
            // handle exception
        } catch (InstantiationException e) {
            // handle exception
        } catch (IllegalAccessException e) {
            // handle exception
        javax.swing.SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                createAndShowGUI();
}I tried using a DefaultTreeCellRenderer and use the setBackgroundSelectionColor() method to null, but it doesn't change anything. Also setting the background of the JPanel to null doesn't make a change when you check with (if(hasFocus)). However I have the impression that nimbus is causing the problem, because if you comment the nimbus part out, you don't have the selection box anymore.
Does anyone has an idea to solve this?
Edited by: Kligham on 30-aug-2010 19:25

Kligham wrote:
Thank you very much!You're welcome.
Kligham wrote:
Problem solved. So since this cell background rendering is a Nimbus "feature", can I assume that the "not displaying of angled lines" also is a Nimbus "feature". Since the JTree tutorial says this should do the trick:
usersTree.putClientProperty("JTree.lineStyle", "Angled");So I probably have to override it the same way, so I was wondering how you know what UIDefaults there are?Well, "JTree.lineStyle" is actually a client property and not a UIDefaults property. In other words, "JTree.lineStyle" is on the same logical level as "Nimbus.Overrides". Unfortunately, there is no way to determine which client properties a component or a component UI implementation supports except carefully examining its source code. javax.swing.plaf.synth.SynthTreeUI (the Nimbus TreeUI implementation) doesn't seem to support any client properties. It might be handled somewhere else, though.
As an alternative to using "JTree.lineStyle", you could try to use a backgroundPainter that draws angle lines instead of the "do nothing" painter I suggested.
To determine which UIDefaults properties are available for a given LaF implementation, you can iterate over the UIDefaults' entrySet (UIDefaults is a subclass of Hashtable). For Nimbus specifically, Jasper Potts already did that. See the [corresponding blog entry|http://www.jasperpotts.com/blog/2008/08/nimbus-uimanager-uidefaults/] and [Nimbus UIDefaults Properties List|http://jasperpotts.com/blogfiles/nimbusdefaults/nimbus.html]

Similar Messages

  • JTree (TreeModel) vs (TreeNode)

    hellow,
    I've got some troubles with a tree-view of my data model: I've created my own TreeModel, implemented the necessary methods, ...
    Now, when I try to display the JTree with the TreeNode parameter (I parse the whole data tree) it works perfectly, but when I'm trying the TreeModel parameter, it only shows the root node (I tried "treeStructureChanged (event)" without result).
    Does someone know what I might be forgetting ?
    Can I add a treenodes manually (might give me a clue what I'm doing wrong in my implementation) ?
    thx alot,
    Jerry

    public class X
    static public TreeNode parseDataModel () { ... }
    // parseDataModel() returns the tree root node.
    tree = new JTree(parseDataModel());
    treeView = new JScrollPane(tree);
    frame.getContentPane().add(treeView, BorderLayout.WEST);
    => this works fine
    public class MyTreeModel implements TreeModel { ... }
    MyTreeModel mtm = new MyTreeModel();
    JTree jTree = new JTree (mtm);
    treeView = new JScrollPane(jTree);
    frame.getContentPane().add(treeView, BorderLayout.WEST);
    => only shows the root node (double-clicking it has no effect; it has no 'folder' icon)

  • JTree get selected node/object values

    I wan to get all the selected nodes/objects values that I added to the JTree. How can I do this?
    Thanks.

    TreePath[] paths = tree.getSelectedPath();
    for(int i = 0; i < paths.length; i++){
    TreeNode node = (TreeNode)paths.getLastPathComponent();
    Object mySelectedObject = node.getUserObject();
    }Some minor Errors
    We have to use array paths[i] instead of paths
    The correct code as used by me is
            javax.swing.tree.TreePath[] paths = jTree1.getSelectionModel().getSelectionPaths();
            for(int i = 0; i < paths.length; i++){
                javax.swing.tree.TreeNode node = (javax.swing.tree.TreeNode)paths.getLastPathComponent();
    System.out.println(((javax.swing.tree.DefaultMutableTreeNode)node).getUserObject());
    CSJakharia

  • JTree leaf selection

    hi guys,
    I am developing a jTree for a networking product,which will show all the network elements present in the network.The tree also shows the device status like Up,Down etc.I have provided a button to refresh the jtree to update the status of the devices.But after updating the jtree when i try to expand or setSelected path to previously selected leaf,the jTree is expanding only till the parent of the leaf.Here is the code which i have written:
    public void addRootNodes()
              TreePath path=jTree.getSelectionPath();
              DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
              TopologyUtilities.getNetworkCollectionDetails();
              TopologyUtilities.getRuntimeDataMapOnRefresh();
              initializeData();
              rootBusiness.removeAllChildren();
              rootNetwork.removeAllChildren();
              rootDiscovery.removeAllChildren();
              addRegionLocationToBusinessView();
              AddNodesToTree.addRoutersToNetworkView(configuredNetworkCollection, dataMap, rootNetwork);
              AddNodesToTree.addRoutersToDiscoveryView(discoveredNetworkCollection, configuredNetworkCollection, dataMap, rootDiscovery);
              treeModel.reload();
              panel.removeAll();
              jTree.setSelectionPath(path);
    Thanks for the help in advance
    bye,
    Srinivas

    Since you have a reference to a DefaultMutableTreeNode object, can't you do something like
    TreeNode[] nodes = n.getPath();
    TreePath path = new TreePath(nodes);
    tree.setSelectionPath(path);

  • JTree and selected tree node

    I am allowing the user to search for a node in a JTree. I can find the node and progamatically expand and select the node. What I would like to do next is find the x,y coordinates of this selected node so I can use Robot to move the mouse to this node. I have hover help which is chock full of information in HTML describing this node, however, the user now is required to move the cursor to this selected node to see the hover help.
    Any help would be appreciated.

    Hi ,
    try this
    jlabel.setIcon( null ) ;

  • Jtree custom selection

    I use the jTree. When an element is selected - i dont like how it looks.
    Check the screenshot : there are two selected areas - a standart one (top) and a custom one(bottom), dont pay attention to the gradient.
    The designer made an improved variant. As you can see, the selection exceeds the jTree and goes over the JPanel, which comprises the jTree.
    How can I make it like this in my app?
    P.S.
    I have an idea to make a half-transparent JPanel and place it over the tree... but I am not sure about the TRUE-ness of this solution :)

    I use the jTree. When an element is selected - i dont like how it looks.
    Check the screenshot : there are two selected areas - a standart one (top) and a custom one(bottom), dont pay attention to the gradient.
    The designer made an improved variant. As you can see, the selection exceeds the jTree and goes over the JPanel, which comprises the jTree.
    How can I make it like this in my app?
    P.S.
    I have an idea to make a half-transparent JPanel and place it over the tree... but I am not sure about the TRUE-ness of this solution :)

  • JTree and selected node question

    Hello
    Is it possible to convert the selected node to an int?
    I guess I'm looking for something llike this.
    int nodeNumber = node.getSelectedIndex();
    There is nothing like that in the API, and it would help greatly if I could find a way do this.
    Thanks
    Have a good holiday
    Jim

    From the API for JTree
    public int getMinSelectionRow()
    Gets the first selected row.
    Returns:
    an integer designating the first selected row, where 0 is the first row in the display
    But I think this is based on how many rows are displayed at the present time and might change if the tree is opened above it.

  • JTree - multiple selection doesn't highlight tree nodes

    I have a JTree which was working great with single selection of objects within it. Now i'm expanding this to work with multiple selected objects at the same time, but the objects are not visibly highlighted in the tree.
    I switched to using DISCONTIGUOUS_TREE_SELECTION, and using setSelectionPaths(TreePath[]) instead of setSelectionPath(TreePath). This works fine, except that the newly selected paths don't visually highlight any more (worked fine with single selection).
    I had thought that the RowMapper was the culprit, but the default VariableHeightLayoutCache seems to be in place and ok. What should i be checking to get this to work right?
    Thanks.

    /me beats forehead against the desk..
    TreePath selectionPath = new TreePath( entityNode.getPath() );
    NOT just
    TreePath selectionPath = new TreePath( entityNode );

  • JTree path selection

    I have a JTree on the left scrollpane and on clicking the value of a node, I display the value in a text field on the right scrollpane. I change the value and set the value in the JTree . I am unable to make the edited tree path selected. The methods provided in the API do not seem to work.

    Don't the JTree.makeVisible( ... ) or JTree.scrollPathToVisible( ... ) methods help?
    kind regards,
    Jos
    Edited by: JosAH on Aug 23, 2009 6:19 PM: typo

  • JTree - Mutiple Selection

    Hi
    I have a JTree and whan to enable mutiple selection i.e. the user holds down the CTRL key and selects as many item as s/he wishes. I tried the follow piece of code but it did not work.
    jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    Any suggestions
    Thanks in advance
    Bernie-wolf

    Hi,
    Well, that is the way that you should set the selection model, and the code does work, so there must be something else going on I would guess.
    What exactly is it doing, and what do you expect it to do?
    If you could post a small code snippet that compiles that shows the problem, then people could run it and debug the problem
    Cheers

  • TreeSelectionListener  valueChanged() called twice on selecting TreeNode

    Hi All,
    This is a class which extends JTree class forms a Tree displaying employee information.Listener is written which should find the list of selected Employee nodes of tree component.
    The method valueChanged() of treeListener is getting called twice for every node selected. Please find the code.
    Is there any alternative to find the list of selected nodes when they are selected using mouse or shift key.
    Even I am facing this in case of row selection of JTable.The listener method is called twice. Could you please let me know your views and any tutorials or examples codes for handling such cases.
    public class TestingTreeModel extends JTree {
         //public vector myMOType;
         public TestingTreeModel() {
              super();
         public void setData(ArrayList testVOs) {
              // set the option of selecting multiple nodes
              this.getSelectionModel().setSelectionMode(
                   TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
              this.setRootVisible(false);
              setModel(rootTreeNode, testVOs);
              // DefaultTreeModel is used.
              this.setModel(new DefaultTreeModel(rootTreeNode));
              // Listener for selected nodes..
              MyTreeSelectionListener myTreeListener = new MyTreeSelectionListener();
              this.addTreeSelectionListener(myTreeListener);
    // which sets the data.
         public void setModel(DefaultMutableTreeNode rootNode, ArrayList empVOs) {
              if empVOs!= null && empVOs.size() > 0) {
                   Iterator empItr = empVOs.iterator();
                   while (neItr.hasNext()) {
                        Employee empVO = (Employee) empItr.next();
                        DefaultMutableTreeNode node =
                             new DefaultMutableTreeNode(empVO.getName());
                        rootNode.add(node);
    // Listener
         public class MyTreeSelectionListener implements TreeSelectionListener {
              public void valueChanged(TreeSelectionEvent evt) {
                   // Get all nodes whose selection status has changed     
                   System.err.println("Listener is called here check how many times");
                   getSelectedNodes(evt);
         private void getSelectedNodes(TreeSelectionEvent evt) {
              System.err.println("came inside getSelectedNodes");
              TreePath[] paths = evt.getPaths();
              // Iterate through all affected nodes
              System.err.println(" Length is " + paths.length);
              for (int i = 0; i < paths.length; i++) {
                   TreePath tp = paths;
                   Object[] o = tp.getPath();
                   for (int j = 0; j < o.length; j++) {
                        System.out.println(
                             "Class: " + o[j].getClass() + "; value: " + o[j]);
                        if (o[j] instanceof DefaultMutableTreeNode) {
                             Object uo = ((DefaultMutableTreeNode) o[j]).getUserObject();
                             if (uo != null) {
                                  System.out.println(
                                       "\tUser object class: "
                                            + uo.getClass()
                                            + "; value: "
                                            + uo);
         private ArrayList empIDList = new ArrayList();
         private DefaultMutableTreeNode rootTreeNode = null;
    Thanks in advance.

    Hi Arun,
    JDev version is Studio Edition Version 11.1.1.5.0.
    Yes, i do have value change listener on the CompanyName LOV. What is a parameter form? The LOV is defined on the page in the following way:
                                <af:selectOneChoice value="#{bindings.CompanyName.inputValue}"
                                                    required="#{bindings.CompanyName.hints.mandatory}"
                                                    shortDesc="#{bindings.CompanyName.hints.tooltip}"
                                                    id="soc1" autoSubmit="true"
                                                    unselectedLabel="--select--"
                                                    contentStyle="width:17em;"
                                                    binding="#{backingBeanScope.backing_Company.soc1}"
                                                    valueChangeListener="#{backingBeanScope.backing_Company.companyChangeListener}">
                                  <f:selectItems value="#{bindings.CompanyName.items}"
                                                 binding="#{backingBeanScope.backing_Company.si1}"
                                                 id="si1"/>
                                </af:selectOneChoice>

  • Jtree leaf selection on jinternal frame

    Hi all,
    I m using a splitpane ...on left hand side i m using a tree and right side i m using a desktoppane where i'll open the internal frames...my tree leaf and internalframe title is same ...
    my question is when when i select any internalframe it should select corresponding leaf(becoz my leaf and t\internalframe is same)...and same i wanna do for tree when i click in any leaf ...internal frame should actived and come to front...
    pls can anyone tell me how to proceed for this...
    can anyone provide me any examples ....pls help me out
    regards
    Tarique

    Since you have a reference to a DefaultMutableTreeNode object, can't you do something like
    TreeNode[] nodes = n.getPath();
    TreePath path = new TreePath(nodes);
    tree.setSelectionPath(path);

  • JTree default selection?

    I've tried searching for this here and there but nothing turned up...
    I was wondering if it is possible to set a default selected item on a JTree.
    So that if no nodes are selected - the first item is selected by default.
    Any hints would be greatly appreciated, thanks.

    If for "nested element" you mean "a node", you can use setSelectionPath(TreePath path) and      setSelectionPaths(TreePath[] paths).
    Message was edited by: java_knight

  • JTree drag selection

    Hello again,
    Can anyone provide some advice on how to implement a drag selection of tree nodes. I don't necassarily need code, just some advice on whats the best practice here. I've been studying how to go about it and my best guess is adding all the mouse listeners to the tree and grabbing coordinate and component width and height info based on mouse released and mouse pressed. Is this the way to do it? Can I use dnd in some way?
    Thanks for any help.
    Shawn

    See if this is of any use http://java.sun.com/products/jfc/tsc/articles/dragndrop/index.html

  • JTree calling setSelectionPath() does not highlight new selection

    I have looked throughout many forum entries and this question has been asked a few times but I have not seen a solution that works at least for me.
    When I do the following:
              TreePath path = new TreePath(...)
    this.tree.setExpandsSelectedPaths(true);          // not sure if I need this
              this.tree.getSelectionModel().setSelectionPath( path ); // this alone should work correct?
              this.tree.scrollPathToVisible(path);
    The original selection disappears (no highlighting) but the new one selected does not
    I have also tried calling just for fun ...
         this.tree.getSelectionModel().resetRowSelection();
    and this.tree.getSelectionModel().reload( path.getLastComponent() );
    Does anybody have an idea of what may be going wrong ? The selection path is valid as I have verified it with the debugger.
    Any ideas or suggestions are much appreciated
    thanks
    Doug

              TreePath path = new TreePath(...)
    The devil is in the details... Unfortunately your case's details are in the ellipsis! :o)
    Try to provide an SSCCE to get informed help, otherwise you can only hope that we guess well. That being said, here is my "guess":
    A preliminary: JTree renders selection by comparing nodes pathes with the selection path(es).
    As is common in the Java world, these comparisons rely on the equals() methods of the objets that make up the TreePath's components.
    If any of the classes involved does not override equals, the corresponding components objects will be considered equals only if they are identical. In other words, a TreePath which contain a "new" instance of whatever class that does not override equals() will never be considered equal to any TreePath created formerly.
    Now comes the gory part: DefaultMutableTreeNode (which is the most often common build block of TreeModels and TreePathes) does not override equals().
    So if your TreePath are made of DefaultMutableTreeNode components, they will never be considered equal unless they use the same DefaultMutableTreeNode instances, which would somewhat not be a common nor practical way of building TreePathes.
    The original selection disappears (no highlighting) but the new one selected does not Under my assumption:
    - the original selection disappears (because by construction the original selection's TreePath it is not equals() to the TreePath passed in argument to setSelectionPath(...)).
    - no new selection is rendered (because by construction no TreePath in the JTree's model can be equals() to the TreePath argument).
    Does anybody have an idea of what may be going wrong ? The selection path is valid as I have verified it with the debugger.Under my assumption:
    - you may have verified that the TreePath seemingly contained the expected values (often rendered in a debugger using toString() calls)
    - you may have overlooked that the TreePath components were not the same references.
    - you may not have executed step-by-step the TreePath.equals() methods nor the equals() method of the path's components.
    Keep in mind that this is just an assumption, based on your code fragment (and on prior painful experience with JTree). If i'm off base and you still need help, please post an SSCCE as sugested previously.
    Edited by: jduprez on Oct 11, 2009 12:53 PM

Maybe you are looking for

  • SAP XI Seeburger and X.400 Adpater

    Hello, We are trying to implement Seeburger X.400 Adapter in our XI 3.0 landscape for the first time. I went through Seeburgers config documentation and did all the setup and still getting errors. Not sure what I missed. At the log it seems to be com

  • Errors when entering responses manually

    I have been encountering an error, when manually entering responses to an existing (and open) Form in Adobe FormCentral. We are currently collecting registrations for an annual event, and the majority of people register online (via the form). However

  • Purchasing music from other stores.

    Hi everyone: Is it possible to do it? I scroll down to select different store, but it logs me out. I can't download anything without changing my billing address but is there another way?

  • Splitter container with alv grid

    I have following coding:     CREATE OBJECT container                   EXPORTING container_name = 'CONTAINER2'.     CREATE OBJECT splitter                   EXPORTING parent = container                             rows    = 2                         

  • Idea on Warehouse builder

    Hi Im new to Warehouse builder and as of now, i've installed Oracle10G warehouse builder. Now i've started working on OWB Client. But i dont know the original purpose of it and other components present in it. Can anybody pls guide me the work flow of