Reputation: 317
I'm trying to write simple application in Java to get all headers only from mail server. Actually everything works well except displaying data in JTable while using DefaultTableModel. The point is that i have about 6k messages in mailbox :P. When i trigger download headers button GUI hangs till last message is received - then i can see everything properly in JTable. JTable is not updating everytime i get header from single message - only after all messages have been downloaded - till then GUI hangs. To find out what is going in i wrote another app adding row's to JTable. There was simple "Application.ProcessMessages" in Delphi updating GUI...i have no idea how to achieve the same in java ( swing )..please help. The code :
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
public class NewApplication extends javax.swing.JFrame {
String[] in;
public NewApplication() {
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
in=new String[5];
in[0]="0";
in[1]="1";
in[2]="2";
in[3]="3";
in[4]="4";
for(Integer r=0;r<5000;r++)
{
try {
add(in);
Thread.sleep(5);
}
catch (InterruptedException ex) {
Logger.getLogger(NewApplication.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void add(String[] in)
{
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{in[0], in[1], in[2],in[3],in[4]});
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewApplication().setVisible(true);
}
});
}
}
What is the simpliest way to update JTable after adding single row ? Regards
Upvotes: 2
Views: 3428
Reputation: 691685
This question is asked almost every day. When you're doing things in the event dispatch thread (like reading 6K messages), you're preventing the event dispatch thread from repainting the GUI.
Long tasks must not be done in the event dispatch thread, but in a separate background thread. Use a SwingWorker. Its javadoc explains how to use it, as well as the swing tutorial.
Upvotes: 6