JList/DefaultListModel持续Insert和Remove数据产生ArrayIndexOutOfBoundsException的问题

来源:互联网 发布:u盘进水数据恢复 编辑:程序博客网 时间:2024/05/02 00:01

      有这样一个需求:往一个JList中持续Insert数据,当JList中的数据量大于某个值时(比如大于5行),就开始删除数据,使得JList中的数据量一直为固定值(如5行),下面是测试代码:

 

上面的测试代码会每隔一段时间就报一个异常:

 

 

经过搜索查找,终于找到问题所在:原来并不是DefaultListModel边界的溢出,而是上面插入/删除数据是在一个新的线程里进行,而界面绘制要求在Event Dispatch Thread中进行,所以当应用程序线程需要更新GUI时,需要把代码包在SwingUtilities.invokeLater()中来处理,使得它们重新回到Event Dispatch Thread中。

 

看看invokeLater的描述:

public static void invokeLater(Runnable doRun)
Causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI. In the following example the invokeLater call queues the Runnable object doHelloWorld on the event dispatching thread and then prints a message.
 Runnable doHelloWorld = new Runnable() {
     public void run() {
         System.out.println("Hello World on " + Thread.currentThread());
     }
 };
 SwingUtilities.invokeLater(doHelloWorld);
 System.out.println("This might well be displayed before the other message.");

 

 

 

把上面测试例子稍微改一下:

 

 

 

 

另外,ArrayIndexOutOfBoundsException也可能是由于数组边界溢出,如果是数组边界溢出,提示应该这个样子的:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 3

 

 

 

 

 

参考:http://www.mofeel.net/858-comp-lang-java-gui/5523.aspx

 

原创粉丝点击