1

I'm using Fest in order to check if two entries have the same icon.

I'm actually having a JTreeFixture, from what i can access a specific entry with its path.

JTreeFixture tree = getTreeFromWindow();
JLabel label  = (JLabel) tree.selectPath("/folder2/entry2").component.getCellRenderer();

JLabel labe2  = (JLabel) tree.selectPath("/folder2/entry3").component.getCellRenderer();

I'm getting two JLabel(s), but they both point to the last entry in my folder2. Since it seems Fest cant help me much here, i'm planning to use the JTree directly (thanks to JTreeFixture.component() => returns the JTree) , and extract the informations directly from the JTree.

How can i get a JLabel included in a JTree, knowing the entry's path ?

SOLVED : I created this method :

public Icon getIconeFromPath(String path){
    JTreeFixture tree = getTreeFromWindow();
    PreMadeCellRenderer renderer = (PreMadeCellRenderer) tree.component().getCellRenderer().;
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.clickPath(path).component().getLastSelectedPathComponent();
    JLabel label = (JLabel) renderer.getTreeCellRendererComponent(tree.component(), node, true, true, true, 0, true);
    return label.getIcon();
}

getTreeFromWindow returns a JTreeFixture PreMadeCellRenderer is a renderer extending DefaultTreeCellRenderer getTreeCellRendererComponent returns a component, and its arguments are explained here http://docs.oracle.com/javase/7/docs/api/javax/swing/tree/TreeCellRenderer.html

I used the parameter 0 because i didnt knew what to put in, and worked :)

Afshin Moazami
  • 2,092
  • 5
  • 33
  • 55
Bertrand
  • 251
  • 1
  • 3
  • 12

1 Answers1

1

Swing uses the same shared JLabel object for painting all the tree nodes (for performance reasons). I would recommend checking the user object (typically a String) of the tree node.

Also see this: Difficulties understanding the renderers mechanism of swing's JTable and JTree

Community
  • 1
  • 1
lbalazscs
  • 17,474
  • 7
  • 42
  • 50
  • Thank's. I already suceeded in reading the UesrObject, and i can read the entries included in my trees, but i'm looking for the icon displayed in the tree – Bertrand Dec 12 '12 at 12:55
  • The icons are also not statically assigned to the tree nodes. You have somewhere a TreeCellRenderer implementation, that assigns an Icon to your node, but this assignment happens only during the painting of your tree. – lbalazscs Dec 12 '12 at 13:25
  • true, i just solved my problem getting the TreeCellRenderer used in the Tree creation, and called getTreeCellRendererComponent with its parameters. I returned a JLabel from what i got my icon ;) – Bertrand Dec 12 '12 at 13:38