java - 按插入顺序获取选定的JTree节点索引

标签 java swing indexing tree jtree

我实现了一个JTree,我需要获取选定节点的索引。

我试图使用以下代码获取索引:

    tree.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {

            // This code to get selected index of node
            int[] selectionRows = tree.getSelectionRows();
        }
    });


但是方法getSelectionRows返回不同的结果,具体取决于是否折叠或扩展了某些节点。例如:

这是我的树:



如果我选择一个节点(如后图),则getSelectionRows返回数字4。



但是,如果某些节点被折叠,如后图所示,则getSelectionRows返回3。

我需要多数民众赞成总是返回4,多数民众赞成在插入节点的顺序的索引数。

谢谢。

最佳答案

如果您尝试跟踪插入顺序,该怎么办?

public class MyTreeModel extends DefaultTreeModel {
  int nodeNum = 0;
  Map<MutableTreeNode,Integer> nodeOrder = ...;

  public void insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) {
    nodeOrder.put(newChild, nodeNum++);
    super.insertNodeInto(newChild, parent, index);
  } 
}

关于java - 按插入顺序获取选定的JTree节点索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637258/

相关文章:

java - 从文件中提取 docID 和文档并将它们放入 HashMap 中

java - 从文件中读取的重音字符在 Eclipse 下与控制台下具有不同的值

java - 找出工作站上的哪个用户启动了程序

mysql - 如何使用索引优化mysql查询?

sql-server - 选择中使用了哪个索引,为什么?

java - spring batch自定义退出描述

java - Maven:打包复制文件夹后复制粘贴WEB-INF到根目录

java BoxLayout面板的对齐方式

java - setEnable(false) 不会阻止 JMenuItem 使用 WindowsLookAndFeel 突出显示

sql-server - 将所有非聚集索引移动到 SQL Server 中的另一个文件组