Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JTree: Selecting all nodes programmatically

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 (){
        @Override
        public void actionPerformed(ActionEvent e) {
                int row = 0;
                while (row < curvesTree.getRowCount())
                {
                    curvesTree.expandRow(row);
                    row++;
                }
            int entradasTree = curvesTree.getRowCount();
            for(int i=0; i<entradasTree; i++){
                TreePath path = curvesTree.getPathForRow(i);
                curvesTree.setSelectionPath(path);
            }
        }
    });

        unselectAll = new JButton("Unselect all");
        unselectAll.addActionListener(new ActionListener (){
            @Override
            public void actionPerformed(ActionEvent e) {
                curvesTree.clearSelection();
            }
        });

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);
curvesTree.setExpandsSelectedPaths(true);
curvesTree.getSelectionModel().setSelectionMode(TreeSelectionModel.
                  DISCONTIGUOUS_TREE_SELECTION);
like image 434
Roman Rdgz Avatar asked Sep 07 '11 11:09

Roman Rdgz


1 Answers

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

 curvesTree.addSelectionPath(...)

EDIT

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());
like image 61
kleopatra Avatar answered Sep 27 '22 22:09

kleopatra