2

我有一个JTable和一个TableModel扩展AbstractTableModel。我想动态设置表中的列数。我通过在我的TableModel命名中添加一个属性来实现这一点column_count,并getColumnCount返回column_count. 我还添加了一个方法,setColumnCount设置column_count和调用fireTableStructureChanged。不幸的是,当我运行程序时,我不断收到ArrayIndexOutOfBounds异常。谁能告诉我我做错了什么,或提出更好的解决方案?

这是一个堆栈跟踪:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4 >= 4 at java.util.Vector.elementAt(Unknown Source) at javax.swing.table.DefaultTableColumnModel.getColumn(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paintGrid(Unknown Source) at javax.swing.plaf.basic.BasicTableUI.paint(Unknown Source) at javax.swing.plaf.ComponentUI.update(Unknown Source) at javax.swing.JComponent.paintComponent(Unknown Source) at javax.swing.JComponent.paint(Unknown Source) at javax.swing.JComponent.paintToOffscreen(Unknown Source) at javax.swing.RepaintManager$PaintManager.paintDoubleBuffered(Unknown Source) at javax.swing.RepaintManager$PaintManager.paint(Unknown Source) at javax.swing.RepaintManager.paint(Unknown Source) at javax.swing.JComponent._paintImmediately(Unknown Source) at javax.swing.JComponent.paintImmediately(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source) at javax.swing.RepaintManager.seqPaintDirtyRegions(Unknown Source) at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source) at java.awt.event.InvocationEvent.dispatch(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

4

3 回答 3

0

您的方法在哪里getValueAt()获取数据?如果它是一个 ArrayList 并且您增加了列大小,那么该表将尝试从列表中获取该列并引发异常。

如果这不是问题,请使用 DefaultTableModel 和DefaultTableModel.addColumn()添加列,或者确保从事件调度线程对表模型进行任何更改。

于 2010-12-07T16:24:24.873 回答
0

我认为异常的原因如下:

  1. 您将内部 column_count 设置为 +1
  2. 您会触发事件,这将导致表格在视觉上更新
  3. 当 JTable 更新代码访问最后一列时,列模型中的内部 Vector 会引发异常。

原因可能是因为 DefaultTableColumnModel 的底层代码不知道新列,并且它的 Vector 没有正确更改。

要解决此问题,您可能应该编写自己的自定义 TableColumnModel 可以正确处理更改尺寸。

于 2010-12-07T22:55:45.050 回答
0

setModel(tm)在我的情况下,调用JTablewith tm the changed方法TableModel 解决了类似的错误。

于 2015-07-29T19:06:11.750 回答