1

I have the following code:

tree = getTreeComponent(BLA)

model = tree.getModel();
root = tree.getModel().getRoot();
childCount = tree.getModel().getChildCount(root);

childList = tree.getModel().getChild(root,x);

print childList

I can get the tree node as a Text but not the Color of Font/Text node.

Could you give me suggestions?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
maxf
  • 19
  • 2
  • 1
    *"could you give me please suggestions?"* See [What is the XY problem?](http://meta.stackexchange.com/q/66377) This sounds like one of them. – Andrew Thompson Nov 04 '14 at 08:35

1 Answers1

4

The appearance of the nodes is separated from the model. TreeCellRenderer is responsible to render the nodes of the tree which can be set using JTree.setCellRenderer().

So if you want to know the Font and Color of a node, you should consult the renderer of the JTree. For example:

Component c = tree.getCellRenderer()
    .getTreeCellRendererComponent(tree, node, false, false, false, 0, false);

Font font = c.getFont();         // Font used to render the node
Color color = c.getForeground(); // Foreground Color used to render the node

The renderer's getTreeCellRendererComponent() returns a Component which will be used to paint the node.

The parameters of the getTreeCellRendererComponent() are:

JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus

Passing different values to these parameters may result in the returned Component having different Font and/or Color. Specify meaningful parameter values (e.g. it should not be selected as it usually inverts the colors, it should not have focus as it might also change the color).

icza
  • 389,944
  • 63
  • 907
  • 827
  • Can you please explain the Parameters (tree, node, false, false, false, 0, false); ? – maxf Nov 04 '14 at 08:27
  • @maxf Read the [JavaDocs](http://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableCellRenderer.html) – MadProgrammer Nov 04 '14 at 08:28
  • You should also add that changing the parameters can change the result, as the node might change its appearance based on the parameters passed to the method ;) – MadProgrammer Nov 04 '14 at 08:29
  • Good answer though ;) – MadProgrammer Nov 04 '14 at 08:31
  • Thank you for Help :) I'm still learning java swing, can you please write me the Example for this : http://stackoverflow.com/questions/17111483/highlighting-specific-nodes-in-a-jtree-depending-on-data-stored-in-the-node – maxf Nov 04 '14 at 10:21
  • but with get function, i cant anderstand how do I get to the required node "Test1" – maxf Nov 04 '14 at 10:22
  • @icza def tree = rc.getComponent("xxxxx") def renderer = tree.getCellRenderer(); def Component c = renderer.getTreeCellRendererComponent(tree,0, false, false, false, 3, false) , i have always error: "avax.swing.tree.TreeCellRenderer$getTreeCellRendererComponent(call:-1)" – maxf Nov 12 '14 at 12:18