简体   繁体   中英

IndexOutOfBoundsException when I try to create a JTable model

When I try to add my JTable to my frame I recieve this error: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

import javax.swing.table.AbstractTableModel;
import java.util.List;
import java.util.ArrayList;

public class tablaFormato extends AbstractTableModel {

List<String[]> topFives = new ArrayList <String[]>();

@Override
public int getColumnCount() {
    // TODO Auto-generated method stub
    return 5;
}

@Override
public int getRowCount() {
    // TODO Auto-generated method stub
    return 5;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {

    Object resultado = topFives.get(rowIndex) [columnIndex];

    return resultado;
}

}

The problem is in resultado but I don't know what I'm doing wrong.

您的getRowCount()应该返回列表的大小,否则您将告诉JTable:“嘿,我有5行”,而实际上您最初有zip,0,zilch。

As the error is trying to tell you, you're trying to get an element from an empty list.
You need to put something in the list before you can get it out.

Your error is surely pointing to the line (see the line number in your exception)

Object resultado = topFives.get(rowIndex) [columnIndex];

The getRowCount() method tells the table how many rows are to display The getColumnCount() method says how many columns are to display in each row

Now the table has enough info to get the data one by one. It starts at row 0, column 0, then row 0 column 1, etc until it reaches what you answered in getColumnCount(). then it goes to row 1 and does the same.

In your case, as soon as it askes for the object in row 0 column 0, an exception is thrown because you're trying to get from topFives an element at the index 0 that doesn't exist.

You have it in the exception: IndexOutOfBoundsException: Index: 0, Size: 0 (you're trying to get the element at 0 (the first), but the size is 0. So the index you're asking for, is out of the bounds of the list)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM