I'm creating a java program that in every second there is a data stored into my table. I made use of THread.sleep(1000) to pause the for loop in every second.. But when my program runs, it freezed for 10 seconds because of the condition of my for loop where the counter has not yet reached 10. So my last choice was to use a Thread that will run on different process so as not to freeze the UI cause i've been doing this with .net.... But the big problem is I dont know how will the created thread will have access to the TABLE object which is at the Mainclass.

From whatever you have posted I assume you need something here where one thread continues the for loop while the other sleeps for 1 sec and then wakes up, is it ? If it is then I suggest you to take a look at the SwingWorker Class. But if it is not I advice the psoting of the relevant code here.

You should never call sleep() in the UI thread (in other words, directly in response to a button click or some other UI handler).

To make the variable visible from another thread, you need to declare it somewhere where it is visible! Possibilities include having a subclass of Thread that you pass the table into:

class TableUpdaterThread extends Thread {
  private final JTable table;
  TableUpdaterThread (JTable t) {
    this.table = t;
  public void run() {
    // thread can now access table

If you make the thread an inner class of your main class where the JTable is defined, then it will be able to see it (inner classes can see variables of their parent).

You also need to think about the tricky issue of thread safety. To cut a long story short, when you perform the actual update to the table, to be completely safe you should do it inside a call to SwingUtilities.invokeLater() rather than directly from the other thread. (You miiight actually get away with not doing so if you're just changing a table model provided the table + model are declared final -- but I wouldn't recommend it.)

SwingWorker may also make things easier for you, as the previous poster mentioned.

Google 'Timer Java'. If I remember correctly, a similar question to this one was asked a few weeks ago, and the solution is to use the Timer class because it is invoked on the Event Dispatch Thread (and thus won't cause problems w/ your GUI stuff)

The problem with the swing Timer is that it will execute the whole task in the GUI thread. So if the task involves:
(1) think about what to add to the table (or retrieve it from DB etc);
(2) actually add it to the table.
you really don't want part (1) executed in the GUI thread.

^ Definitely worth considering. If there is much processing involved in getting/generating those rows, adding them to the table model through EventQueue.invokeLater() may work out better. It's difficult to say, given how little detail was supplied.

This article has been dead for over six months. Start a new discussion instead.