Is there a way to prevent a JTree from loosing it's selection when it
looses focus? Say I have a few items selected in the JTree and then I
go to press a button, that normally causes the JTree to unselect
everything, how can I stop this?
I don't have this behaviour on my machine (Windows XP, Java 1.5.0_10).
When I run the following program, select some tree nodes and press the
button at the bottom, it prints out the selected paths as it should.
Maybe it's your code that has a problem, but you don't show us
anything.
JB.
package foo;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
public class TreeTest extends JFrame {
public TreeTest() {
super("Tree test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
root.add(new DefaultMutableTreeNode("child1"));
root.add(new DefaultMutableTreeNode("child2"));
root.add(new DefaultMutableTreeNode("child3"));
TreeModel treeModel = new DefaultTreeModel(root);
final JTree tree = new JTree(treeModel);
getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
JButton button = new JButton("Print selection");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
TreePath[] selectedPaths =
tree.getSelectionModel().getSelectionPaths();
if (selectedPaths != null) {
for (TreePath tp : selectedPaths) {
System.out.println(tp);
}
}
}
});
getContentPane().add(button, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
TreeTest t = new TreeTest();
t.setVisible(true);
}
}