简体   繁体   中英

Add a row to a jTable each pass through a loop?

I have a jTable and a 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. 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. 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. 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. I've also tried using a Swing Timer but to no avail. 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. In addition to the create your own Thread and use SwingUtilties.invokeLater(), you can also use the newer of approach of using a SwingWorker. The tutorial contains an example.

I've tried calling 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.

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 . The table will request that it be repainted, and that request will go on the EDT. Unfortunately, your long running process is holding up other requests from getting handled on the 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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