Custom TreeCellRenderer

I've written a custom TreeCellRenderer that extends DefaultTreeCellRenderer. Each node in the tree has an object associated with it, and depending on that object, a different icon is used by the renderer (its not a file system, but similar).
The problem is that when you edit a node, the default icons are used. The custom renderer is being used by the TreeCellEditor (also custom), but I think it is using the getXXXXIcon() methods rather than the getTreeCellRendererComponent method.
The solution seems to be to override the getTreeCellEditorComponent() method in the TreeCellEditor class, but apart from the icon this is doint exactly what I want it to do.
Is there an easy way to change the icon it will use without causing too much carnage?

I wanted to make sure I was correct, but I wasn't.import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.util.Random;
public class Test2 extends JFrame {
  static final ImageIcon[] icons = { new ImageIcon("icon1.gif"),
                                     new ImageIcon("icon2.gif") };
  public Test2() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container content = getContentPane();
    DefaultMutableTreeNode root = new DefaultMutableTreeNode(
                                              new MyObject("root", icons[0]));
    JTree jt = new JTree(root);
    jt.setCellRenderer(new MyRenderer());
    Random r = new Random();
    for (int i=0; i<5; i++) {
      DefaultMutableTreeNode child = new DefaultMutableTreeNode(
                  new MyObject("Child-"+i,icons[r.nextInt(icons.length)]));
      root.add(child);
      for (int j=0; j<5; j++) {
        DefaultMutableTreeNode gchild = new DefaultMutableTreeNode(
                    new MyObject("Grandchild-"+j,icons[r.nextInt(icons.length)]));
        child.add(gchild);
      content.add(new JScrollPane(jt), BorderLayout.CENTER);
    setSize(300,300);
  public static void main(String[] args) { new Test2().setVisible(true); }
class MyObject {
  String text;
  Icon icon;
  public MyObject(String text, Icon icon) { this.text=text; this.icon=icon; }
  public String toString() { return text; }
  public Icon getIcon() { return icon; }
class MyRenderer extends DefaultTreeCellRenderer {
  public Component getTreeCellRendererComponent(JTree tree, Object value,
                                                boolean sel, boolean exp,
                                                boolean leaf, int row,
                                                boolean focus) {
    Component c = super.getTreeCellRendererComponent(tree, value, sel, exp, leaf,
                                                row, focus);
    if (value instanceof DefaultMutableTreeNode) {
      Object val = ( (DefaultMutableTreeNode) value).getUserObject();
      if (val instanceof MyObject) {
        System.out.println("Yes");
        setIcon( ( (MyObject) val).getIcon());
      } else System.out.println("No: " + val.getClass());
    return c;
}

Similar Messages

  • Determing which component from a custom TreeCellRenderer was clicked on

    hi,
    i've been experimenting with finding which component has been clicked on in a JTree which has a custom tree cell renderer. I've got a piece of code that appears to work, but am unsure if this is the proper way to go about doing this, and whether it might fail under some circumstances.
    any help appreciated,
    asjf
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    public class JTreeTest1 {
       public static void main(String[] arg) throws Exception {
          final JTree tree = new JTree();
          final TreeCellRenderer renderer = new MyRenderer();
          tree.setCellRenderer(renderer);
          tree.addMouseListener(new MouseAdapter() {
             public void mouseClicked(MouseEvent e) {
                int x = e.getX(), y = e.getY();
                int row = tree.getRowForLocation(x,y);
                TreePath path = tree.getPathForLocation(x,y);
                if(path!=null) {
                   Object o = path.getLastPathComponent();
                   Rectangle r = tree.getPathBounds(path);
                   // how to detect what component has been clicked on?
                   // simplification: pretend all boolean state has no effect on renderer (which is true for the renderer below)
                   Component renderedComponent = renderer.getTreeCellRendererComponent(tree, o, false, false, false, row, false);
                   renderedComponent.setBounds(r);
                   int _x = (int) ((double)e.getX() - r.getX());
                   int _y = (int) ((double)e.getY() - r.getY());
                   Component clickedUpon = SwingUtilities.getDeepestComponentAt(renderedComponent, _x, _y);
                   if(clickedUpon instanceof JLabel) {
                      JLabel jl = (JLabel) clickedUpon;
                      System.out.println(jl.getText());
          JFrame frame = new JFrame("JTreeTest1");
          frame.getContentPane().add(tree);
          frame.pack();
          frame.setVisible(true);
    class MyRenderer extends JPanel implements TreeCellRenderer {
       JLabel custom;
       public MyRenderer() {
          super(); // flow layout
          add(new JLabel("Hello"));
          add(custom = new JLabel());
          custom.setOpaque(true);
          custom.setBackground(UIManager.getColor("Tree.background"));
          custom.setForeground(UIManager.getColor("Tree.foreground"));
          add(new JLabel("World"));
       public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded,
                                                     boolean leaf, int row, boolean hasFocus)
          custom.setText("("+value.toString()+")");
          return this;
    }

    My only advice would be to remember that rendered components are not actually added to the tree, so they are not a child of the tree... they actually cannot be clicked on. The rendered components are quickly used just to paint and specific image and then discarded (which is why you don't typically want to create new ones each time). When you click on the tree, there is no "rendered component" there, just an image that was painted.
    Hope this helps
    Josh Castagno
    http://www.jdc-software.com

  • Selection background color in a custom TreeCellRenderer

    I'm trying to write a custom TreeCellRender and I'm not having any luck getting the selection to work. When I click on a node (leaf or not) the color of the node does not change. If I use the default renderer instead of my custom renderer selection works fine. I've tried everything I can find on the web, setOpaque(true) setTextSelectionColor() etc but I'm not getting anywhere. I've also tried setting the background color in getTreeCellRendererComponent() based on the selected boolean. Still nothing.
    Here's my code:
    class PackageTreeRenderer extends DefaultTreeCellRenderer {
         public PackageTreeRenderer() {
              setOpaque(true);
              setTextSelectionColor(getBackgroundSelectionColor());
         public Component getTreeCellRendererComponent(JTree t,Object value,boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
              Object obj = node.getUserObject();
              if(obj instanceof String) {
                   String name = (String) obj;
                   setText(name);
              if(obj instanceof ResultPackageInterface) {
                   ResultPackageInterface rpi = (ResultPackageInterface) obj;
                   String name = "Name";
                   try {
                        name = rpi.getDescription();
                   catch(RemoteException ex) {
                        errorMessage(ex);
                   setText(name);
              if(leaf) {
                   setIcon(getLeafIcon());
              else {
                   if(expanded) {
                        setIcon(getOpenIcon());
                   else {
                        setIcon(getClosedIcon());
              return this;
    }Hope someone can help.

    Thanks for the suggestions everyone but I got it working. Instead of extending DefaultTreeCellRenderer it works if I extend JLabel and implement TreeCellRenderer. Here's my code for future reference:
    class PackageTreeRenderer extends JLabel implements TreeCellRenderer {
         public PackageTreeRenderer() {
              setOpaque(true);
         public Component getTreeCellRendererComponent(JTree t,Object value,boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus) {
              DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
              Object obj = node.getUserObject();
              setText(obj.toString());
              if(obj instanceof String) {
                   String name = (String) obj;
                   setText(name);
              if(obj instanceof ResultPackageInterface) {
                   ResultPackageInterface rpi = (ResultPackageInterface) obj;
                   String name = "Name";
                   try {
                        name = rpi.getDescription();
                   catch(RemoteException ex) {
                        errorMessage(ex);
                   setText(name);
              if(leaf) {
                   setIcon(UIManager.getIcon("Tree.leafIcon"));
              else {
              if(expanded) {
                   setIcon(UIManager.getIcon("Tree.openIcon"));
              else {
                   setIcon(UIManager.getIcon("Tree.closedIcon"));
              if(sel) {
                   setForeground(UIManager.getColor("Tree.selectionForeground"));
                   setBackground(UIManager.getColor("Tree.selectionBackground"));
              else {
                   setForeground(UIManager.getColor("Tree.textForeground"));
                   setBackground(UIManager.getColor("Tree.textBackground"));
              return this;
    }

  • JTree Custom TreeCellRenderer problem on Mac OS + Firefox

    Hi,
    I have a JApplet containing a JTree component with custom renderer that implements TreeCellRenderer to display CheckBox along the tree nodes.
    Everything works fine on Window and Linux OS (firefox browser)
    Problem is with :
    Firefox + Mac: applet fails to load because getTreeCellRendererComponent() does not seem to get invoked.
    Appreciate you time and thoughts on the problem.
    Edited by: rg18mar on Nov 27, 2007 10:31 PM

    Our only other environment we could set up was on Mac OS 10.7.5, and we could not reproduce the issue.  Based on that it would appear to be something new with Mac OS 10.8.

  • Custom TreeCellRenderer not working in Program

    The following 2 lines set my TreeCellRenderer
    FSDirectoryCellRenderer renderer1 = new FSDirectoryCellRenderer();
    jtree.setCellRenderer(renderer1);
    Rendering is not working in the Below Program. But If I comment the above 2 lines the default rendering is working. There is a probelm with my rendering class FSDirectoryCellRenderer which I am not able to figure out. PLease help me out
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.SoftBevelBorder;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;
    public class UniversityLayout extends JFrame {
         private JTree jtree = null;
         private DefaultTreeModel defaultTreeModel = null;
         private JTextField jtfStatus;
         public UniversityLayout() {
              super("A University JTree Example");
              setSize(300, 300);
              Object[] nodes = buildJTree();
              DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
              renderer.setOpenIcon(new ImageIcon("opened.gif"));
              renderer.setClosedIcon(new ImageIcon("closed.gif"));
              renderer.setLeafIcon(new ImageIcon("leaf.gif"));
              jtree.setCellRenderer(renderer);
              jtree.setShowsRootHandles(true);
              jtree.setEditable(false);
              jtree.addTreeSelectionListener(new UTreeSelectionListener());
              FSDirectoryCellRenderer renderer1 = new FSDirectoryCellRenderer();
              jtree.setCellRenderer(renderer1);
              JScrollPane s = new JScrollPane();
              s.getViewport().add(jtree);
              getContentPane().add(s, BorderLayout.CENTER);
              jtfStatus = new JTextField(); // Use JTextField to allow copy operation
              jtfStatus.setEditable(false);
              jtfStatus.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
              getContentPane().add(jtfStatus, BorderLayout.SOUTH);
              TreePath path = new TreePath(nodes);
              jtree.setSelectionPath(path);
    //          jtree.scrollPathToVisible(path);
         class FSDirectoryCellRenderer extends JLabel implements TreeCellRenderer {
              private Color textSelectionColor;
              private Color textNoSelectionColor;
              private Color backgroundSelectionColor;
              private Color backgroundNoSelectionColor;
              private boolean sel;
              public FSDirectoryCellRenderer() {
                   super();
                   textSelectionColor = UIManager.getColor("Tree.selectionForeground");
                   textNoSelectionColor = UIManager.getColor("Tree.textForeground");
                   backgroundSelectionColor = UIManager
                             .getColor("Tree.selectionBackground");
                   backgroundNoSelectionColor = UIManager
                             .getColor("Tree.textBackground");
                   setOpaque(false);
              public Component getTreeCellRendererComponent(JTree tree, Object value,
                        boolean selected, boolean expanded, boolean leaf, int row,
                        boolean hasFocus) {
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                   Object obj = node.getUserObject();
                   setText(obj.toString());
                   if (obj instanceof Boolean) {
                        setText("Loading");
                   if (obj instanceof NodeIconData) {
                        NodeIconData nodeIconData = (NodeIconData) obj;
                        if (expanded) {
                             setIcon(nodeIconData.getExpandedIcon());
                        } else {
                             setIcon(nodeIconData.getNormalIcon());
                   } else {
                        setIcon(null);
                   setFont(jtree.getFont());
                   setForeground(selected ? textSelectionColor : textNoSelectionColor);
                   setBackground(selected ? backgroundSelectionColor
                             : backgroundNoSelectionColor);
                   sel = selected;
                   return this;
         private Object[] buildJTree() {
              Object[] nodes = new Object[4];
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(new College(1, "College"));
              DefaultMutableTreeNode parent = root;
              nodes[0] = root;
              DefaultMutableTreeNode node = new DefaultMutableTreeNode(new College(2, "Class 1"));
              parent.add(node);
              parent = node;
              parent.add(new DefaultMutableTreeNode(new College(3, "Section A")));
              parent.add(new DefaultMutableTreeNode(new College(4, "Section B")));
              parent = root;
              node = new DefaultMutableTreeNode(new College(5, "Class 2"));
              parent.add(node);
              nodes[1] = node;
              parent = node;
              node = new DefaultMutableTreeNode(new College(6, "Science"));
              parent.add(node);
    //          nodes[2] = node;
              parent = node;
              parent.add(new DefaultMutableTreeNode(new College(7, "Computer Science")));
              parent.add(new DefaultMutableTreeNode(new College(8, "Information Science")));
              parent = (DefaultMutableTreeNode)nodes[1];
              node = new DefaultMutableTreeNode(new College(9, "Arts"));
              parent.add(node);
              nodes[2] = node;
              parent = (DefaultMutableTreeNode)nodes[2];
              parent.add(new DefaultMutableTreeNode(new College(10, "Drawing")));
              node = new DefaultMutableTreeNode(new College(11, "Painting"));
              parent.add(node);
              nodes[3] = node;
              parent = (DefaultMutableTreeNode)nodes[1];
              parent.add(new DefaultMutableTreeNode(new College(12, "Telecom")));
              defaultTreeModel = new DefaultTreeModel(root);
              jtree = new JTree(defaultTreeModel);
              return nodes;
         public static void main(String argv[]) {
              UniversityLayout frame = new UniversityLayout();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
         class UTreeSelectionListener implements TreeSelectionListener {
              public void valueChanged(TreeSelectionEvent e) {
                   TreePath path = e.getPath();
                   Object[] nodes = path.getPath();
                   String status = "";
                   for (int k = 0; k < nodes.length; k++) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes[k];
                        College nd = (College) node.getUserObject();
                        status += "." + nd.getId();
                   jtfStatus.setText(status);
    class College {
         protected int id;
         protected String name;
         public College(int id, String name) {
              this.id = id;
              this.name = name;
         public int getId() {
              return id;
         public String getName() {
              return name;
         public String toString() {
              return name;
    }

    It works fine for me (after commenting out the part about NodeIconData, whose source you didn't provide). What is the behavior you expect to see but don't? Is it that when you click on a tree node, it doesn't appear "selected?"
    Why not extends DefaultTreeCellRenderer? You appear to be doing minimal configuring (sometimes changing the text and/or icon of the node).
         class FSDirectoryCellRenderer extends DefaultTreeCellRenderer {
              public FSDirectoryCellRenderer() {
                   super();
                   setOpaque(false);
              public Component getTreeCellRendererComponent(JTree tree, Object value,
                        boolean selected, boolean expanded, boolean leaf, int row,
                        boolean hasFocus) {
                   super.getTreeCellRendererComponent(tree, value, selected, expanded,
                                       leaf, row, hasFocus);
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                   Object obj = node.getUserObject();
                   setText(obj.toString());
                   if (obj instanceof Boolean) {
                        setText("Loading");
    //               if (obj instanceof NodeIconData) {
    //                    NodeIconData nodeIconData = (NodeIconData) obj;
    //                    if (expanded) {
    //                         setIcon(nodeIconData.getExpandedIcon());
    //                    } else {
    //                         setIcon(nodeIconData.getNormalIcon());
    //               } else {
                        setIcon(null);
                   return this;
         }

  • Custom JTree TreeCellRenderer with JPanel

    I have developed a custom TreeCellRenderer which extends JPanel to allow multple icons to be displayed and changed as the context changes. The JPanel has one or two icons and a JLabel which I control based on display context. The renderer works fine with one exception. If the initial string displayed beside the icons is short (such as 4 characters) when I try to display it with a longer string the JPanel does not resize to allow displaying the entire string. I've tried several variation to get the JPanel to resize. I've exanined the code in operation and it seems as though the size of the JLabel is being change correctly and the setPreferredSize on the JPanel is changing correctly. It just wont display without truncating the longer JLabel.
    I've reviews the forum to no avail.
    The code follows. Any thoughts are appreciated
    import javax.swing.ImageIcon;
    import java.awt.Image;
    import javax.swing.JLabel;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.JTree;
    import com.logixpartners.planlogix.insuranceobject.*;
    import com.logixpartners.planlogix.utility.RtnObject;
    import java.awt.*;
    public class PLIconLabel extends javax.swing.JPanel implements TreeCellRenderer {
    ImageIcon a,b;
    int fWidth = 0;
    int sWidth = 0;
    String text = "";
    JLabel one, two, three;
    InsObject io;
    boolean selected;
    FontMetrics fontMetrics;
    int iconHeightPad = 0;
    int fontH, fontLen, iconH = 30+iconHeightPad;
    /** Creates a new instance of PLIconLabel */
    public PLIconLabel() {
    super(null); //null indicates no layour manager
    one = new JLabel();
    one.setIconTextGap(0);
    two = new JLabel();
    two.setIconTextGap(0);
    three = new JLabel();
    three.setIconTextGap(0);
    add(one);
    add(two);
    add(three);
    public void setIconOne(ImageIcon i) {
    a = i;
    fWidth = a.getImage().getWidth(this);
    one.setBounds(0,0, fWidth, a.getImage().getHeight(this)+iconHeightPad);
    if (b != null) {
    two.setBounds(fWidth,0,sWidth,b.getImage().getHeight(this)+iconHeightPad);
    three.setBounds(fWidth+sWidth+5,0,fontLen, iconH);
    one.setIcon(a);
    repaint();
    public void removeIconOne() {
    a = null;
    fWidth = 0;
    if (b != null) {
    two.setBounds(fWidth,0,sWidth,b.getImage().getHeight(this)+4);
    three.setBounds(fWidth+sWidth+5,0, fontLen, iconH);
    one.setIcon(a);
    repaint();
    public void setIconTwo(ImageIcon i) {
    b = i;
    sWidth = b.getImage().getWidth(this);
    two.setBounds(fWidth,0,sWidth,b.getImage().getHeight(this)+iconHeightPad);
    three.setBounds(fWidth+sWidth+5,0, fontLen, iconH);
    two.setIcon(b);
    repaint();
    public void removeIconTwo() {
    b = null;
    sWidth = 0;
    two.setIcon(b);
    two.setBounds(fWidth,0,0,0);
    three.setBounds(fWidth+sWidth+5,0,fontLen, iconH);
    repaint();
    public void setPLText(String t) {
    text = t;
    three.setText(t);
    fontMetrics = three.getFontMetrics(three.getFont());
    fontLen = fontMetrics.stringWidth(t);
    fontH = fontMetrics.getHeight();
    three.setBounds(fWidth+sWidth+5,0,
    fontLen+10,
    fontH);
    repaint();
    public java.awt.Component getTreeCellRendererComponent(JTree tree,
    Object value,
    boolean sel,
    boolean expanded,
    boolean leaf,
    int row,
    boolean hasFocus) {       
    try {
    io = (InsObject)value;
    } catch (java.lang.ClassCastException e) {
    e = e;
    setPLText(io.getBestName());
    if (io.getTypeOf().equals("Ref")){
    setPLText(io.getAttribute("Name"));
    // Setup colors for node selection
    if (sel) {
    setBackground(new java.awt.Color(64,128,128));
    } else {
    setBackground(new java.awt.Color(95,167,152));
    // Change text color of node
    three.setForeground(sel ? java.awt.Color.white : java.awt.Color.black);
    // Get proper Icon for Node
    if ((io.getClass().getName()).equals("com.logixpartners.planlogix.insuranceobject.InsObjectRef")){
    setIconTwo( (ImageIcon)((RtnObject)PLIcons.getIcon((String)io.getTypeOf())).getReturnValue());
    setIconOne((ImageIcon)PLIcons.get("RefPtr") );
    } else {
    removeIconOne();
    if (!expanded && !leaf) {
    setIconTwo( (ImageIcon)((RtnObject)PLIcons.getIconX((String)io.getTypeOf())).getReturnValue());
    } else {
    setIconTwo( (ImageIcon)((RtnObject)PLIcons.getIcon((String)io.getTypeOf())).getReturnValue());
    two.setToolTipText((String)io.getTypeOf());
    selected = sel;
    Dimension dim = new Dimension(three.getWidth()+60+fWidth+sWidth+20,iconH);
    setPreferredSize(dim);
    setMinimumSize(dim );
    setMaximumSize(dim );
    setSize(dim);
    validate();
    return this;
    }// end of class

    Addition to my original post. I found a forum post noting a similar problem. The suggest fix was to set the JTree row heigth to 0 (zero) and to add a getPreferredSize in the TreeCellRenderer, which gets called when row height is zero, and explicitly set the desired size. This works but with an exception. It seems as though the getPreferredSize is only called once when it is a leaf node being rendered. This seems to be true for expand, collaspe, and select.

  • Making JTree custom renderer panel scalable

    Hi, everyone. I have made custom TreeCellRenderer which extends JPanel. Panel's background is in different color than JTree's backgound. I need to get my panel rendering the nodes to fill the whole space JTree has in it's parent panel horizontally. For now I have put static width to nodes and it looks fine, but it's not scalable. If I don't put any sizes the panel takes only the size it needs in cell and the outfit is crappy because of panel's different bgcolor. Is there any easy way to make rendering panel use the width which JTree has in it's container. I have implemented getPreferredSize() method in custom TreeCellRenderer and now it returns the static width and height of the rendering panel. Do I have to get JTrees container panel's width every time and pass it to renderer and get size somehow from there or is there some easier way.
    -e

    Yes, there is a reason. Different levels of nodes contain different components. Example main level nodes have print and save buttons on the most right of the panel. Only leafs have same bgcolor as the tree has and those are already now scalable, because size is not set for them.

  • JPanel custom tooltips in JTree not showing

    Hi,
    I use a custom TreeCellRenderer in a JTree like
    MyTreeCellRenderer extends JPanel implements TreeCellRenderer
    The panel contains two JLabels, each with a different tooltip. Although I register the tree, the panel and the two labels with the tootipmanager, no tooltips are showing up. Any idea?
    Thanks,
    Ulrich

    I'll provide my own answer:
    As it currently stands Logic Apps require a "default" response to be defined in the swagger. This is not implemented by default by an API app out of the box, but can be done relatively easily by adding a Swagger OperationFilter.
    That is to say in the
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    method of the filter you will need to ensure that the operation.responses dictionary contains an entry keyed with 'default'.
    Microsoft's provided connectors contain a reference to a "Microsoft.Azure.BizTalk.Adapters.SwaggerGenerator.dll" contains a OperationFilter that will do this for you if you don't want to write one yourself.
    Final note: Having spoken to MS about this issue it is currently under review and will hopefully be resolved in a future version of LogicApps so hopefully this will all disapear.
    Edit: Also see http://blogs.msdn.com/b/hosamshobak/archive/2015/03/31/logic-app-with-simple-api-app-with-inputs-and-outputs.aspx

  • JTree Not Using TreeCellRenderer

    I am using a custom TreeCellRenderer in a JTree to do various things
    (checkbox, icons, etc..) I have it working for most users 90% of the
    time. However, sometimes the TreeModel and TreeCellRenderer do not get
    picked up. I put some System.out.println statements in to help me
    debug, and found that the JTree is being returned invalid every once
    and a while.
    javax.swing.JTree[,0,0,0x0,invalid,alignmentX=null,alignment�Y=null,border=,flags=360,maximumSize=,minimumSize=,preferred�Size=,editable=false,invokesStopCellEditing=false,largeModel�=false,rootVisible=true,rowHeight=16,scrollsOnExpand=true,sh�owsRootHandles=false,toggleClickCount=2,visibleRowCount=20] I am just creating this normally (i.e. jTree = new JTree()). I then
    turn around and set the TreeModel and TreeCellRenderer in, but I assume
    that it is not going to pick them up because it is invalid.
    Does anyone know why the tree would sometimes be invalid, and how I can
    go about preventing it from becomming invalid? Any help is
    appreciated.
    Thanks-
    John

    John,
    i don't think "invalid" in this context means anything like "the tree is invalid, ie has no renderer or data model". it might have something to do, if it is "validated" etc.
    when you say that the renderer/model does not get picked up, what exactly do you mean by this?
    what is the effect?
    what do you mean by "for most users"? when does it not work?
    i do what you describe a lot and works fine for me everytime...
    thomas

  • TreeCellRenderer in Linux

    Hi!
    I'm trying to get my swing app to work in both Windows and Linux. Right now, it works in Windows, but in Linux (Mandrake) it returns a ClassCastException in the getTreeCellRendererComponent() method in my custom TreeCellRenderer. My app shows a filesystem tree.
         public Component getTreeCellRendererComponent(
             JTree tree,
             Object value,
             boolean selected,
             boolean expanded,
             boolean leaf,
             int row,
             boolean hasFocus) {
                   String name=fsv.getSystemDisplayName(((FileNode)value).getFile());  // CLASSCASTEXCEPTION HERE
                   super.getTreeCellRendererComponent(tree, name, selected, expanded, leaf, row, hasFocus);
                   setText(name);
                   setIcon(fsv.getSystemIcon(((FileNode)value).getFile()));
                   return this;
         }I don't know why the FileNode class cast throws a ClassCastException in Linux but not in Windows. Here is the code for the FileNode class:
    public class FileNode extends DefaultMutableTreeNode {
         private FileSystemView fsv=FileSystemView.getFileSystemView();               
         public FileNode(String name) {
              setUserObject(new File(name));
         public FileNode(File file) {
            setUserObject(file);
         public boolean getAllowsChildren() {
                 return isDirectory();
         public boolean isLeaf() {
                 return !isDirectory();
         public File getFile() {
                 return (File)getUserObject();
         public boolean isDirectory() {
              File file = getFile();
              return fsv.isTraversable(file).booleanValue();
    }Can anyone help me, please ? Is FileSystemView broken in Linux ? I'm using 1.4.2 in both Windows (the full JSDK) and Linux (the JRE).
    leemon

    You do know the difference between "new topic" and "reply", do you?

  • Problemns with JTree

    Hi! I'm having problems with the Tree cell renderer. I must render a tree that have leafs that is also JPanels compounded by a checkbox, an icon and a the text label. It's supposed to alter the state of the checkbox when clicked or when press the spacebar over the cell, but it isn't working...
    If I set the tree as editable (down in the code, in main method), the checkbox is selected only after the second click, but the cell is not being highlighted and cannot collapse the category nodes. Otherwise, when set the Tree as NOT editable, the highlight of cell and the rest works, but obviously I cannot edit the checkboxes...
    Can someone help me, please?
    package test;
    import com.interact.sas.ResourceLocator;
    import com.interact.sas.dms.*;
    import com.interact.sas.ui.UserIconLabel;
    import java.awt.*;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import java.util.EventObject;
    import java.util.Vector;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.tree.*;
    public class DocumentControllerTreeTest
        static class MyTreeCellEditor extends AbstractCellEditor implements TreeCellEditor, TreeCellRenderer
            private static Icon iconCategory = ResourceLocator.getIcon( "sas/dms/tb_categories.png" );
            private static Border noFocusBorder = new EmptyBorder( 1, 1, 1, 1 );
            private JPanel cell = new JPanel();
            private JCheckBox checkRequired = new JCheckBox();
            private UserIconLabel userIconLabel = new UserIconLabel();
            private DocumentControllerTree.Item currentItem = null;
            public MyTreeCellEditor()
                userIconLabel.setOpaque( false );
                checkRequired.setOpaque( false );
                cell.setLayout( new BorderLayout() );
                cell.add( checkRequired, BorderLayout.WEST );
                cell.add( userIconLabel, BorderLayout.CENTER );
                cell.addKeyListener( new KeyAdapter()
                    public void keyPressed( KeyEvent e )
                        if ( e.getKeyCode() == KeyEvent.VK_SPACE )
                            checkRequired.setSelected( ! checkRequired.isSelected() );
                            e.consume();
                cell.addMouseListener( new java.awt.event.MouseAdapter()
                    public void mouseClicked(java.awt.event.MouseEvent evt)
                        checkRequired.setSelected( ! checkRequired.isSelected() );
             * getCellEditorValue
             * @return Object
            public Object getCellEditorValue()
                currentItem.getController().setRequired( checkRequired.isSelected() );
                return new Boolean( currentItem.getController().isRequired() );
             * getTreeCellEditorComponent
             * @param JTree tree,
             * @param Object value,
             * @param boolean isSelected,
             * @param boolean expanded,
             * @param boolean leaf,
             * @param int row
             * @return Component
            public Component getTreeCellEditorComponent( JTree tree,
                    Object value,
                    boolean isSelected,
                    boolean expanded,
                    boolean leaf,
                    int row)
                return getTreeCellRendererComponent( tree, value, isSelected, expanded, leaf, row, true );
             * getTreeCellRendererComponent
             * @param JTree tree,
             * @param Object value,
             * @param boolean selected,
             * @param boolean expanded,
             * @param boolean leaf,
             * @param int row,
             * @param boolean hasFocus
             * @return Component
            public Component getTreeCellRendererComponent( JTree tree,
                    Object value,
                    boolean isSelected,
                    boolean isExpanded,
                    boolean isLeaf,
                    int row,
                    boolean hasFocus )
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                Object object = node.getUserObject();
                if ( object instanceof DocumentControllerTree.Item )
                    currentItem = (DocumentControllerTree.Item) object;
                    checkRequired.setSelected( currentItem.getController().isRequired() );
                    //checkRequired.setSelected( !checkRequired.isSelected() );
                    int action = currentItem.getController().getAction();
                    if ( action == DocumentController.ACTION_APROVE ||
                            action == DocumentController.ACTION_VERIFY )
                        checkRequired.setVisible( true );
                    else
                        checkRequired.setVisible( false );
                    userIconLabel.setFont( tree.getFont() );
                    userIconLabel.setUser( currentItem.getUser() );
                    userIconLabel.setText( currentItem.getUser().getName() );
                else
                    // nunca poderia chegar aqui ...
                    checkRequired.setVisible( false );
                    userIconLabel.setFont( tree.getFont() );
                    userIconLabel.setIcon( ! isLeaf ? iconCategory : null );
                    userIconLabel.setText( object.toString() );
                if ( isSelected )
                    cell.setBackground( UIManager.getColor( "Tree.selectionBackground") );
                    cell.setForeground( UIManager.getColor( "Tree.selectionForeground") );
                else
                    cell.setBackground( tree.getBackground() );
                    cell.setForeground( tree.getForeground() );
                Border border = noFocusBorder;
                if (hasFocus)
                    if (isSelected)
                        border = UIManager.getBorder("List.focusSelectedCellHighlightBorder");
                    if (border == null)
                        border = UIManager.getBorder("List.focusCellHighlightBorder");
                cell.setBorder(border);
                return cell;
        public static void main( String[] args )
            try
                DocumentControllerTree tree = new DocumentControllerTree();
                DocumentManager dm = DocumentManager.getInstance();
                DocumentCategory dc = dm.getCategory( 32 );
                Vector<DocumentController> vdc = dm.getControllers( dc );
                tree.setCellRenderer( new MyTreeCellEditor() );
                tree.setCellEditor( new MyTreeCellEditor() );
                tree.setCategory( dc );
                tree.setControllers( vdc );
                // This must be true
                //tree.setEditable( true );
                JScrollPane scroller = new JScrollPane( tree );
                scroller.setPreferredSize( new Dimension( 240, 320 ) );
                JOptionPane.showMessageDialog( null, scroller );
            catch ( Exception e )
                e.printStackTrace();
            System.exit( 0 );
    }

    OK, here's briefly what I'd do:
    1
    In your tree constructor, set a custom TreeCellRenderer. (I assume your tree extends JTree.)
    2
    Create a custom TreeCellRenderer by extending JPanel and implementing TreeCellRenderer. In the getTreeCellRendererComponent method, remember you don't have to use a component that you have around. You use the tree node's text: tree.convertValueToText(value, sel, expanded, leaf, row, hasFocus)); This returns a string. The string could be "true" or "false". You then create a JCheckBox based on this value. Add the JCheckBox to �this�, i.e. to the custom TreeCellRenderer that extends a JPanel. Return �this�. Remember that once �this� is returned, the value is forgotten and the JCheckBox is unclickable. (What you click actually is the TreeCellRenderer, that then decides you want to focus a node and thereafter passes focus and subsequent clicks to your panel and/or the TreeCellEditor).
    3
    Back to the tree constructor. Set your TreeCellEditor to a custom class of yours. Copy the code from DefaultCellEditor. There is a constructor in DefaultCellEditor that accepts a JCheckBox as sole argument. Try that one. In an inner class in DefaultCellEditor, EditorDelegate, you'll find the stopCellEditing method. Override it and make sure to convert boolean values back to "true" or "false" in the tree node, so that the renderer will have the right value to work with.
    From there on, I guess things should work by themselves. (Warning: completely unchecked!!!) If not, at least the code is sufficiently separated for us to know where it fails (renderer, editor, tree...)
    PS. Second thought: DefaultMutableTreeNode accepts an Object as object, not only a string. Maybe you could use a boolean value or a Boolean object directly in the tree node instead of strings...
    Just my 2 cents

  • 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]

  • JTree Cell Renderer Problem

    Hi can someone help me please??
    I've created a JTree with a custom TreeUI which paints the JTree's backround with gradient paint.
    The problem i'm having is that i want to make the background color of the treecells transparent, no color at all. In my custom TreeCellRenderer it works fine setting the foreground color and everything, but not the background...
    Any clues anyone?

    Figured it out right after this post :)
    I had to do the following in my cellrenderer
    setBackgroundNonSelectionColor(new Color(0, 0, 0, 0));As a parameter I sent a color object with a alpha level of 0 (completly transparent)...

  • Setting background color for entire row of a JTree

    Hi,
    I'm trying to figure out how I can define the component for the entire width of a row of a JTree, not just a section after the arrow and indentation as by implementing a custom TreeCellRenderer.
    Any help would be appreciated.
    Thanks.

    The arrow is part of the UI. You may be able to do this by changing your UI settings The arrow is called a handle - you can set custom handle icons so that may be one approach. Someone else may have a better idea.

  • Highlight root node in jtree

    When I build my JTree, I have just one single node, the root node. So in order to highlight it, I basically do setSelectionRow(0);, however this is not highlighting the node as if a user clicked it with a mouse, WHEN THE APPLICATION COMES UP.
    Once the application comes up, if I click on that node or for that matter any other node, they get highlighted in blue. It's only upon initialization that this doesn't work.
    Here's a snippet of the sample code:
    tree = new JTree();
    tree.setCellRenderer(new RateManagerTreeCellRenderer());
    I've also tried the setSelectionPath(TreePath path) method without any success. I think that my Custom TreeCellRenderer could be the culprit. If someone could try to duplicate this problem by using the code below of my RateManagerTreeCellRenderer, I would appreciate it.
    public class RateManagerTreeCellRenderer extends DefaultTreeCellRenderer
    private static Color oldColor = Color.BLACK;
    private static Color newColor = Color.BLUE;
    private HashMap iconMap = new HashMap();
    public Component getTreeCellRendererComponent(
              JTree tree, Object value,
              boolean selected, boolean expanded,
              boolean leaf, int row,
              boolean hasFocus)
    super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)value;
    Object userObject = treeNode.getUserObject();
    if (userObject instanceof NameAndID)
    NameAndID nameAndID = (NameAndID)userObject;
    int count = nameAndID.getItemCount();
    if (count > 0 && !selected)
    setForeground(newColor);
    else if (!selected)
    setForeground(oldColor);
    this.setToolTipText(((NameAndID)userObject).toString());
    String type = nameAndID.getType();
    setIcon(type);
    return this;
    }

    Do you mean setting the focus on that node? Or are you talking about some custom painting to put a background behind it? We can't help you much if you don't ask a more specific question with more details about what you're trying to do.

Maybe you are looking for

  • Ipod wont show up in itunes after installing update

    okay so i hadn't updated my ipod in a couple of months (bad i know but we have really slow internet here and it takes forever to download things) then i downloaded the update a couple of days ago and it started installing then came up with an error s

  • Mac Pro not recognizing bootable DVDs and Disk Utility giving odd results.

    My issue is complex, but I'll try my best to explain it as I can. One has been resolved it seems, but I am including it so that the whole issue can be seen in context. Friday, May 16, 2014 Last night, after rebooting my Mac Pro from my Bootcamp parti

  • Average daily requirements in MD04

    Hi gurus, Can anybody please help me in understanding in how the system is calcualting the average daily requirements for the following settings of the coverage profile. Period indicator - Weeks (W) Number of periods - 12 Type of period length - 1 (w

  • Infocube Requests - Data Selection

    Hi Gurus, In the Infocube there were 4 requests, i want to know the selection conditions used in those requests apart from the place Infocube -> Manage -> Request tab. I need to use that information in ABAP codings, so please give the information lik

  • Simple selector question

    Don't know why I can't figure this out, but In my html page I have the following simple text which are directions to an office: <div id="maincontent">    <p>FROM THE         LONG ISLAND EXPRESSWAY: Get off at exit 37, Willis Ave. Then follow the dire