简体   繁体   English

JTree:以编程方式选择所有节点

[英]JTree: Selecting all nodes programmatically

I have a Jtree, and 2 buttons to select and unselect all nodes. 我有一个Jtree和2个按钮来选择和取消选择所有节点。 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. 取消选择按钮似乎在起作用,但是全选仅展开JTree并选择最后一个节点。 I think every time a node is selected programatically, I'm unselecting the former one. 我认为每次以编程方式选择一个节点时,我都不会取消选择前一个节点。

JTree is configured like this: JTree的配置如下:

curvesTree = new JTree(rootNode);
curvesTree.setExpandsSelectedPaths(true);
curvesTree.getSelectionModel().setSelectionMode(TreeSelectionModel.
                  DISCONTIGUOUS_TREE_SELECTION);

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: 即使多年之后,阅读api仍然具有启发性;-)刚刚发现了一种非常简单的方法,该方法将所有工作留给了树:

tree.setSelectionInterval(0, tree.getRowCount());

I would like to add to kleopatra's answer (based on my own growing pains). 我想增加kleopatra的答案(根据我自己的成长痛苦)。

In my particular problem, I needed to add a "Select All Children" menu item to the JTree node popup menu. 在我的特定问题中,我需要向JTree节点弹出菜单添加“选择所有子项”菜单项。 Therefore, this solution applies to all children of a selected node. 因此,此解决方案适用于所选节点的所有子级。

TreeNode selectedNode = tree.getSelectionPath().getLastPathComponent();
// Expand tree from selected node...
List<TreePath> paths = new ArrayList<TreePath>();
determineTreePaths(selectedNode, paths); // Recursive method call...

TreePath[] treePaths = new TreePath[paths.size()];
Iterator<TreePath> iter = paths.iterator();

for (int i = 0; iter.hasNext(); ++i)
{
   treePaths[i] = iter.next();
}

if (paths.size() > 0)
{
   TreePath firstElement = paths.get(0);
   setSelectionPath(firstElement);
   scrollPathToVisible(firstElement);
}    

The determineTreePaths(selectedNode, paths) recursive call is needed to traverse the tree from the selected node all the way down to the leaf nodes. 要从选择的节点一直到叶节点遍历树,需要确定树determineTreePaths(selectedNode, paths)递归调用。 This solution works regardless of depth (to the best of my knowledge). 就我所知,此解决方案无论深度如何都有效。 What I cannot say is that it is the most efficient solution. 我不能说的是,这是最有效的解决方案。 Anyone with a better solution, please feel free to post a different solution or edit this one. 有更好解决方案的任何人,请随时发布其他解决方案或编辑此解决方案。

The method implementation is as follows: 方法实现如下:

private void determineTreePaths(TreeNode currentNode, List<TreePath> paths)
{
   paths.add(new TreePath(((DefaultTreeModel) getDefaultTreeModel()).getPathToRoot(currentNode));

   // Get all of my Children
   Enumeration<?> children = currentNode.children();

   // iterate over my children
   while (children.hasMoreElements())
   {
      TreeNode child = (TreeNode) children.nextElement();
      determineTreePaths(child, paths);
   }
}

yes is that possible, for example: 是的,这是可能的,例如:

import java.awt.Dimension;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;

public class TreeWithMultiDiscontiguousSelections {

    public static void main(String[] argv) {
        JTree tree = new JTree();
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
        int treeSelectedRows[] = {3, 1};
        tree.setSelectionRows(treeSelectedRows);
        TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent treeSelectionEvent) {
                JTree treeSource = (JTree) treeSelectionEvent.getSource();
                System.out.println("Min: " + treeSource.getMinSelectionRow());
                System.out.println("Max: " + treeSource.getMaxSelectionRow());
                System.out.println("Lead: " + treeSource.getLeadSelectionRow());
                System.out.println("Row: " + treeSource.getSelectionRows()[0]);
            }
        };
        tree.addTreeSelectionListener(treeSelectionListener);
        JFrame frame = new JFrame("JTree With Multi-Discontiguous selection");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JScrollPane(tree));
        frame.setPreferredSize(new Dimension(380, 320));
        frame.setLocation(150, 150);
        frame.pack();
        frame.setVisible(true);
    }

    private TreeWithMultiDiscontiguousSelections() {
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM