Roman Rdgz Roman Rdgz - 1 year ago 107
Java Question

JTree: Selecting all nodes programatically

I have a Jtree, and 2 buttons to select and unselect all nodes. I made an attempt like this:

selectAll = new JButton("Select all");
selectAll.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {
int row = 0;
while (row < curvesTree.getRowCount())
int entradasTree = curvesTree.getRowCount();
for(int i=0; i<entradasTree; i++){
TreePath path = curvesTree.getPathForRow(i);

unselectAll = new JButton("Unselect all");
unselectAll.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {

The unselect button seems to be working, but the select all only expands the JTree and selects the last node. I think every time a node is selected programatically, I'm unselecting the former one.

JTree is configured like this:

curvesTree = new JTree(rootNode);

Answer Source

the unselect happens because you are setting a new selection path instead of adding. In the loop after expanding, instead do



reading api is always instructive, even after years ;-) Just found a much simper method, which leaves all the work to the tree:

tree.setSelectionInterval(0, tree.getRowCount());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download