0

I am trying to display instructions for calculating Empirical Formulas given element percents. The logic works right now but when I try to display instructions, I am given the following error:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 1
at javax.swing.JTable$1.getValueAt(Unknown Source)
at javax.swing.JTable.getValueAt(Unknown Source)
at javax.swing.JTable.prepareRenderer(Unknown Source)

This appears only when I click the button to display the instructions on how the formula is calculated. There is no trouble instantiating the data array nor the JTable, but when I try to render the JTable, these errors occur. The JTable's TableHeader renders fine, but the JTable itself doesn't. Here is the code:

public void giveInstructions() {
    String[] columnNames = { "Atom", "Percent", "Molar Mass", "Divide by Molar Mass", "Divide by Smallest Moles",
            "Coefficient" };
    Object[][] data = new Object[6][elemInForm];
    for (int i = 0; i < elemInForm; i++) {
        data[0][i] = elementEnter[i];
    }
    for (int i = 1; i < 6; i++) {
        for (int j = 0; j < elemInForm; j++) {
            data[i][j] = Float.valueOf(elemVals[i-1][j]);
            System.out.println(j);
            System.out.println(i);
        }
    }
    inst4Empir = new JTable(data, columnNames);
    inst4Empir.setPreferredScrollableViewportSize(new Dimension(700, 700));
    inst4Empir.setFillsViewportHeight(true);

    instructions.add(inst4Empir.getTableHeader(), BorderLayout.PAGE_START);
    instructions.add(inst4Empir, BorderLayout.CENTER);
    // instructions.pack();
    instructions.setVisible(true);
}

}

The error occurs with the instructions.add(inst4Empir, BorderLayout.CENTER); and with instructions.setVisible(true); The problem isn't with entering the values into the array and an ArrayIndexOutOfBoundsException happening there.

EDIT: The problem is happening with the display at instructions.add(inst4Empir, BorderLayout.CENTER);. The array is being initialized and populated just fine. When the display is trying to render it, the JTable causes an OutOfBoundsException. I have printed the values being used to populate the array and they are fine.

K_R
  • 1
  • 1
  • Welcome to SO. TL;DR. Please Post a [MCVE] : post the bare minimum to show your issue. (Writing a minimal case is a good debugging technique. In doing so you are likely to solve your problem.) – c0der Mar 19 '17 at 04:15

1 Answers1

0
java.lang.ArrayIndexOutOfBoundsException  

happens when the array size is less than the datas inserting into the array. for example:-

public static void main(String[] args) {
    int[] arr = new int[3];
    arr[0] = 3;
    arr[1] = 4;
    arr[2] = 5;
    arr[3] = 5;
}

here exception happens at arr[3]=5 when trying to save value into an unallocated memory space (index = 3).