maxf
maxf

Reputation: 19

JTree: how to get the Font/text color of the node?

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?

Upvotes: 1

Views: 1320

Answers (1)

icza
icza

Reputation: 418435

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).

Upvotes: 4

Related Questions