gpt4 book ai didi

java - JTable.removeColumn() 方法抛出异常

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:32:27 26 4
gpt4 key购买 nike

为了仅在 JTable 的 View 中隐藏列,我使用了 removeColumn() 方法。但是它抛出异常

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 7 >= 7
at java.util.Vector.elementAt(Vector.java:470)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:294)
at javax.swing.plaf.basic.BasicTableHeaderUI.paint(BasicTableHeaderUI.java:648)

我认为,从 View 中删除列后,如果我修改了模型,则会弹出此异常。是因为在 View 中没有列,而模型正在更新表吗?

在 JTable 中隐藏 View 中的列的最佳方法是什么?而不是将大小设置为 0

编辑:异常不会定期发生。这是一个随机的异常(exception)。无论如何,这是代码:

    @Override
protected Object doInBackground() throws Exception {
........
resultDTO=//get data from database
tableModel.setDataVector(resultDTO.getAllRows(), tableModel.getColumnNames());
// hide column
table.removeColumn(table.getColumnModel().getColumn(7));
System.out.println("table column count : " + table.getColumnCount());
System.out.println("model column count : " + tableModel.getColumnCount());
........
.........
}



initial result (with out any data in table, at application startup):
table column count : 7
model column count : 8

after populating data (first running of above method):
table column count : 7
model column count : 8

after few times executing :
table column count : 7
model column count : 8
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 7 >= 7
at java.util.Vector.elementAt(Vector.java:470)
at javax.swing.table.DefaultTableColumnModel.getColumn(DefaultTableColumnModel.java:294)
at javax.swing.plaf.basic.BasicTableHeaderUI.paint(BasicTableHeaderUI.java:648)
at javax.swing.plaf.synth.SynthTableHeaderUI.paint(SynthTableHeaderUI.java:173)

有时我第一次加载数据时会出现上述异常,有时不会。

最佳答案

您正在尝试更新 Event Dispatching Thread 之外的 UI 组件, 这绝不是一个好主意

protected Object doInBackground() throws Exception {
........
resultDTO=//get data from database
// This shouldn't be done here
tableModel.setDataVector(resultDTO.getAllRows(), tableModel.getColumnNames());  
// and neither should this
// hide column
table.removeColumn(table.getColumnModel().getColumn(7));

虽然使用了 SwingWorker,但还是竖起大拇指。问题是,Swing 组件不是线程安全的,您永远不应该尝试在 EDT 之外更新它们,因为它们会导致意外结果(就像您刚刚遇到的那样)。

与其直接设置行数据,我建议使用 publish/process 方法。如果您不能决定何时删除该列,我会在 worker 执行之前或在 worker done 方法

中删除它

关于java - JTable.removeColumn() 方法抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12224650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com