简体   繁体   English

每次通过一个循环向jTable添加一行?

[英]Add a row to a jTable each pass through a loop?

I have a jTable and a jButton. 我有一个jTable和一个jButton。 When clicked, the button's actionPerformed method calls another method that contains a while loop and adds a row to the table's model (DefaultTableModel) each time though the loop. 单击时,按钮的actionPerformed方法调用另一个包含while循环的方法,并在每次循环时向表的模型(DefaultTableModel)添加一行。 The while loop can run for a few minutes so I want it to show in the GUI the rows being added to the table each time, one by one. while循环可以运行几分钟,所以我希望它在GUI中显示每次添加到表中的行,一个接一个。 However right now it adds all the rows to the table together after the loop is finished, so instead of incrementing the number of rows one by one over the course of a few minutes it goes from a few minutes of showing a table with 0 rows to then instantly having thousands. 但是现在它在循环结束后将所有行一起添加到表中,所以不是在几分钟内逐个递增行数,而是从显示0行的表的几分钟到然后立刻有成千上万。 I've tried calling updateUI, repaint etc on the table as well as calling fireTabledDataChanged etc on the model but none of this made any difference. 我试过在表上调用updateUI,重绘等,以及在模型上调用fireTabledDataChanged等,但这没有任何区别。 I've also tried using a Swing Timer but to no avail. 我也试过使用Swing Timer但无济于事。 I'd appreciate any help or guidance offered, thanks. 我很感激提供任何帮助或指导,谢谢。

Read the section from the Swing tutorial on Concurrency which explains in more detail about how the EDT works. 阅读Swing教程中的Concurrency部分,该部分详细介绍了EDT的工作原理。 In addition to the create your own Thread and use SwingUtilties.invokeLater(), you can also use the newer of approach of using a SwingWorker. 除了创建自己的Thread并使用SwingUtilties.invokeLater()之外,您还可以使用更新的方法来使用SwingWorker。 The tutorial contains an example. 本教程包含一个示例。

I've tried calling updateUI, 我试过调用updateUI,

Never do something like that. 永远不要做那样的事情。 Even if it fixes your problem, it is the wrong solution. 即使它解决了您的问题,也是错误的解决方案。 You are not updating the UI, you are updating a component. 您没有更新UI,而是要更新组件。

If you are using a DefaultTableModel , calling addRow on your model during each iteration should update the model, which should then in turn update the JTable . 如果您使用的是DefaultTableModel ,则在每次迭代期间在模型上调用addRow应该更新模型,然后应该更新JTable The table will request that it be repainted, and that request will go on the EDT. 该表将要求重新绘制,该请求将在EDT上进行。 Unfortunately, your long running process is holding up other requests from getting handled on the EDT. 不幸的是,您的长时间运行过程会阻止其他请求在EDT上处理。 The best thing for you to do is have your button trigger a process in a worker thread, and that thread could then have its addRow calls performed in a Runnable that gets dropped onto the EDT via SwingUtilities.invokeLater 你要做的最好的事情就是让你的按钮在工作线程中触发一个进程,然后该线程可以在Runnable中执行addRow调用,该调用通过SwingUtilities.invokeLater被放到EDT上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM