Вопрос

I'm doing a chess game and I need to make a log table that prints every move. The LogTable class is like this:

public class LogTable {
    private DefaultTableModel model;
    private JTable table;
    public LogTable(JPanel panel){
        String[] columnNames = {"Move No.",
                                "White",
                                "Black"};

        model = new DefaultTableModel(columnNames, 0);
        table = new JTable();
        //model.isCellEditable(i, i1)
        table.setModel(model);

        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        //Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(table);

        panel.add(scrollPane);
    }

    public void newMove(chessPiece piece){
        if (piece.getColor() == 0){
            Object[] newRow = new Object[3];
            newRow[0] = model.getRowCount()+1;
            newRow[1] = piece.sayPos();
            newRow[2] = " ";
            model.addRow(newRow);
        }
        else {
            model.setValueAt(piece.sayPos(), model.getRowCount(), model.getColumnCount());
        }
    }
}

But in the first black move it thows an ArrayOutOfBoundsException. The newMove function is called at the chessPiece class:

public void move(int newX, int newY, JPanelSquare jPanelSquareGrid[][], LogTable logTable){
    resetShowValidMoves(jPanelSquareGrid);
    logTable.newMove(this);
}

The rest of the move code is in each piece, which call super. I'm using the DefaultTableModel.

Это было полезно?

Решение

From Java API :

public DefaultTableModel(Object[] columnNames,int rowCount)

Constructs a DefaultTableModel with as many columns as there are elements in columnNames and rowCount of null object values. Each column's name will be taken from the columnNames array.

You instantiate the DefaultTableModel with 0 rows. So you can't set the value of an item in row 0 since it doesn't exist.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top