【问题标题】:java - JTable setValueAt not workingjava - JTable setValueAt 不工作
【发布时间】:2014-04-29 06:20:51
【问题描述】:

我正在做一个国际象棋游戏,我需要制作一个记录每一步棋的日志表。 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 swing netbeans jtable indexoutofboundsexception


    【解决方案1】:

    来自Java API

    public DefaultTableModel(Object[] columnNames,int rowCount)
    

    构造一个 DefaultTableModel,其列数与其中的元素数一样多 null 对象值的 columnNames 和 rowCount。每列的名称 将从 columnNames 数组中获取。

    您使用 0 行实例化 DefaultTableModel。所以你不能设置第 0 行中的项目的值,因为它不存在。

    【讨论】:

    • true 但是白棋的第一步总是添加一个新行。但无论如何,我最终发现了错误。 getRowCount() 和 getColumnCount() 返回值从 1 开始,但是对于 setValueAt 处的索引,我需要从 0 开始使用,所以我只是从它们中减去 1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    相关资源
    最近更新 更多