JTable ArrayIndexOutOfBoundsException

-2 java swing jtable

为什么以下代码会产生java.lang.ArrayIndexOutOfBoundsException: 0 >= 0

JTable oTable = new JTable();
for (int row = 0; row < table.getRowCount(); row++) {
  for (int column = 0; column < table.getColumnCount(); column++) {
    oTable.setValueAt(table.getValueAt(row, column), row, column);
  }
} 
Run Code Online (Sandbox Code Playgroud)

表已使用SortKeys进行排序.在SortKeys工作之后,GUI中的视图会更新,但基础数据(模型)尚未更改.我需要更改底层模型或使用视图中的数据创建一个新表.

DefaultTableModel model = (DefaultTableModel) table.getModel();
TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
List<RowSorter.SortKey> sortKeys = new ArrayList<RowSorter.SortKey>();
sortKeys.add(new RowSorter.SortKey(model.findColumn("col title"), SortOrder.DESCENDING));
sortKeys.add(new RowSorter.SortKey(model.findColumn("col title 2"), SortOrder.DESCENDING));
sortKeys.add(new RowSorter.SortKey(model.findColumn("another col title"), SortOrder.DESCENDING));
sorter.setSortKeys(sortKeys); //this should trigger a .sort()
Run Code Online (Sandbox Code Playgroud)

我不知道为什么模型不会更新,但事实并非如此.

Hov*_*els 5

您正在使用两个JTable变量,oTabletable,并且oTableJTable有0列和0行,但表引用的JTable可能没有.这将导致Java查找不存在的行和列.不要以这种方式混合和匹配JTable变量.

如果您希望表和oTable JTable保持相同的值,只需将模型传递给:

oTable.setModel(table.getModel());
Run Code Online (Sandbox Code Playgroud)