1

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);
            }
        }
    });
}
Gary Klasen
  • 1,001
  • 1
  • 12
  • 30
  • 2
    Consider providing a [runnable example](https://stackoverflow.com/help/mcve) which demonstrates your problem. This is not a code dump, but an example of what you are doing which highlights the problem you are having. This will result in less confusion and better responses – MadProgrammer Aug 19 '15 at 00:27
  • Thanks for your quick reply. Just edited and hope it now will be less confusing. – Gary Klasen Aug 19 '15 at 00:44
  • 1
    "My array has to be empty, but it is not!" Look for EDT violations, as suggested [here](http://stackoverflow.com/q/7787998/230513). – trashgod Aug 19 '15 at 02:28

0 Answers0