我正在玩国际象棋游戏,我需要制作一个打印每一步棋的日志表。 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/