java - JTable setValueAt 不工作

标签 java swing netbeans jtable indexoutofboundsexception

我正在玩国际象棋游戏,我需要制作一个打印每一步棋的日志表。 LogTable类是这样的:

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

但是在第一个黑棋中它抛出一个 ArrayOutOfBoundsException。 newMove 函数在 chessPiece 类中被调用:

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

其余的移动代码在每个片段中,调用 super.我正在使用 DefaultTableModel。

最佳答案

来自 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.

您用 0 行实例化 DefaultTableModel。因此,您无法设置第 0 行中某个项目的值,因为它不存在。

关于java - JTable setValueAt 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22566283/

相关文章:

Java 最大递增有序子序列

java - 响应休息分页请求的正确方法

java - 如何解密X509证书签名

java - 使 Java Swing 在 Windows 中接受用户输入路径(从资源管理器复制粘贴路径)

php - 将 netbeans 和 PHP 从 Win 迁移到 Ubuntu - 什么目录结构?

java - [学习EJB] : annotation type is not applicable to this kind of declaration?

Java:并行过滤大文本文件,同时保持顺序

java - 在 JTable 中显示哈希表数据?

java - 尝试使用 JCheckBox 作为 JButton (Java Swing)

java - 自动完成 jcombobox java netbeans