"AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0 in Swing's JTree

326 views Asked by At

Here is the exception i am getting, when i am trying to save the first value of int[] to a simple primitive. The array is part of a JTree.

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

I studied other topics for a while now and mostly found the answer, that logically my array has to be empty. But it is not! Other references to multidimensional arrays and vectors also play no role.

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();
}

So, the value of the first entry is 4 and the only entry made (size 1). Also, it can not be null. So why is System.out.println() able to read, but a reference to the int can not be made?

Always when I select a row from the tree, it is saved during the first click in MouseEvent. The method is called after a TreeSelectionListener was added.

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);
            }
        }
    });
}
0

There are 0 answers