1

这是我得到的例外,当我试图将第一个值保存 int[]到一个简单的原语时。该数组是 a 的一部分JTree

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0

我研究了一段时间的其他主题,大部分都找到了答案,逻辑上我的数组必须是空的。但事实并非如此!对多维数组和向量的其他引用也不起作用。

private void paintSelectionRect() {

    // Get selected row bounds:
    System.out.println("Test "+tree.getSelectionRows()[0]); // Output: Test
    System.out.println("Size "+tree.getSelectionRows().length); // Output: Size 1

    if (tree.getSelectionRows() == null) {
        selectedRowBounds = null;
        return;
    }

    int row = tree.getSelectionRows()[0]; // Exception!

    selectedRowBounds = tree.getRowBounds(row);
    // Repaint the JTree:
    tree.repaint();
}

因此,第一个条目的值是 4,并且是唯一的条目(大小 1)。此外,它不能为空。那么为什么System.out.println()可以阅读,但int不能进行参考呢?

总是当我从树中选择一行时,它会在第一次单击时保存MouseEvent。在添加a 之后调用该方法TreeSelectionListener

TreeSelectionModel selectionModel = tree.getSelectionModel();

    selectionModel.addTreeSelectionListener(new TreeSelectionListener() {

         public void valueChanged(final TreeSelectionEvent e) {
            paintSelectionRect();
        }
    });

    tree.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            int row = tree.getClosestRowForLocation(e.getX(), e.getY());

            if (e.getClickCount() == 2) {
                if (tree.isCollapsed(row)) {
                    tree.expandRow(row);
                } else {
                    tree.collapseRow(row);
                }
            } else {
                tree.setSelectionRow(row);
            }
        }
    });
}
4

0 回答 0