I want to create a specific gui.
I have a JTree that can already list the items i want to show (from a database). Now i want to but buttons (radiobuttons would be the best) next to some specific elements of the JTree... And by clicking on the OK button at the bottom of the screen i want to reach the state of those buttons and the ID of the specific element that is in that row to be able to make changes in my data.
I've done something similar in the past with check boxes, so I have a little experience
Step one: maintain a mapping to tree paths to selected states. A Map<TreePath,Boolean> could do, or a Set<TreePath> that only contains the selected tree paths.
Step two: the renderer. This is my class with check boxes (modified slightly):
Step three: the editor (you can skip this if you make your tree read-only):
Step four: make sure this renderer and editor are used:
Step five: add the mouse listener. My example is simple; when anywhere on the tree item is clicked the state is toggled:
The toggle selection is easy with a JCheckBox, but with a JRadioButton it may be a bit harder; just calling setSelected(false) doesn't work always.
The repaint is necessary or you won't see the changes. The easy way is to call revalidate() and repaint() on the tree, but firing a treeNodesChanged event (see TreeModelListener) would be better.
If you only want to catch clicks on the actual check box / radio button, that's a bit harder but still possible. In pseudo code:
Please note that I haven't tested this last part, but I've done something similar in a JTable and that worked just fine.
Joined: Feb 09, 2009
Thank you for your help, i managed to solve the problem with the help of the example code.