Am working on a project in swings and in that am adding rows to a JTable in a while loop.
My Scenario is this :-
As soon as the user clicks a button the program enters a while() loop and start adding rows to the DefaultTableModel of the Jtable one by one till the while loop terminates. But the thing is that the table gets updated with the data only after the while loop has ended.I want it to update after adding each row and show it on the UI.
It would be really nice if someone could help me out with this provide a solution
I have already tried repaint() after adding each row but开发者_JAVA百科 it didn't work.
You need to run your operation in a seperate thread and then update the JTable in the gui thread. Something like this:
public void someButtonClicked(params...) {
new Thread(new Runnable() {
public void run() {
longOperation();
}
}).start();
}
public void longOperation() {
for(int i=0; i<1000; i++) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// add new row to jtable
}
});
}
}
i think you should go for frequently updating the row. There is a tutorial given by sun called the "Christmas tree". Here is link for that
http://java.sun.com/products/jfc/tsc/articles/ChristmasTree/
Above link will help you for frequently update rows in jTable.
If your entire while loop is running on the Swing event dispatch thread in response to the button click event, the thread will not be free to update the view on the screen until your event-handling code completes (the end of your actionPerformed method).
I'm not sure what you're trying to accomplish here -- animation perhaps? You could use Swing's Timer class (javax.swing.Timer) to fire an event repeatedly with a small delay between firings, and in response to each event you could add a row to the table. As long as your event-handling code exits quickly in response to each event fired, Swing should be able to redraw the view in between events. You really need to understand Swing's threading model pretty well or these types of problems are really confusing. It's not too difficult -- there are good resources out there to read if you search for e.g. "Swing event thread."
Re: calling repaint() -- this won't work as repaint() and the other methods like validate() etc. will only ever flag a component as needing to be repainted -- the component won't actually be repainted on screen until Swing gets a chance to do this, and if you are trapping the Swing thread in a while loop, it won't be free to do the painting until you end your loop and your event handling code finishes.
精彩评论