1

I am trying to insert multiple row in JTable using for loop. I m doing this on button click event. I want JTable to display/reflect each row immediately on UI after i insert it. but it is not reflecting until button click event complete.

I tryied repaint(),model.reflectdatachange(), validate(). and all other method but no luck. can someone please help here.

Note: All data is reflecting but after loop finish execution or we can say after button click action complete.


    DefaultTableModel tableModel = new DefaultTableModel(null,new String[] {"Sr","Server", "Status"});
    JTable jTable1=new JTable();
    jTable1.setModel(tableModel_1);
    //above code set from somewhere


    //iterating over Arraylist withing button click

    int table2_row_index=0; 
    for(String host:hostList){
        //inserting table row
        tableModel.insertRow(table2_row_index, new Object[] {table2_row_index+1,host,"some string"});

        //Expected to reflect this row on UI immediately.so tried repaint((),revalidate(), fireTableDataChanged() and other but still row not reflecting until button-click event execute completely.


        /* executing other code*/

        //updating column 
        tableModel_2.setValueAt("updated string", table2_row_index, 2);
        table2_row_index++;
    }

Vaibhav Nandkule
  • 39
  • 1
  • 1
  • 2
  • 2
    Swing is single threaded and all code that updates a Swing component should be executed on the Event Dispatch Thread (EDT). If you have long running code that executes when you click the button, then the code should be moved to a separate Thread. Try using a `SwingWorker` and then you can publish is row of the table as the data is received. Read the section from the Swing tutorial on [Concurrency](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for more information on the `EDT` and on a `SwingWorker`. – camickr May 24 '20 at 23:00
  • [For example](https://stackoverflow.com/questions/17414109/populate-jtable-with-large-number-of-rows/17415635#17415635) – MadProgrammer May 24 '20 at 23:11
  • 1
    **Thank you so much [camickr](https://stackoverflow.com/users/131872/camickr)**, for this details explanation..I was not knowing about this. I studied EDT and [Concurrency](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) and implemented the same and its working now. Also found some helpful [tutorial](https://www.geeksforgeeks.org/swingworker-in-java/) for the same. Thanks once again. – Vaibhav Nandkule May 25 '20 at 10:22
  • 1
    **Thanks [Madprogrammer](https://stackoverflow.com/users/992484/madprogrammer)**. example you provided is also very well explained.Thanks for the help. – Vaibhav Nandkule May 25 '20 at 10:32

0 Answers0