views:

70

answers:

3

In my java swing application am having a Jframe and Jlabel for displaying current time. here am using a thread for displaying time in jlablel which is added to the frame.my doubt is that when i dispose the jframe what will happen to the thread whether its running or stopped.

+1  A: 

If you have NOT marked your thread as daemon by calling yourThread.setDaemon(true), it will keep running even if main thread in your application has finished. Remember you have to call setDaemon before starting the thread.

Refer my answer to some previous question for details.

The correct way in your case, I believe, would be you maintain a 'stop' flag which is watched by your timer thread. Timer thread should exit on reading this flag as 'false'. You can add a WindowListener to your jframe and on the window closed event set the 'stop' flag to true

Heres example code for what I am suggesting :

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

public class JFrameTest {

  public static void main(String[] args) {

    final Timer t = new Timer();
    t.start();

    JFrame jf = new JFrame("GOPI");
    jf.setVisible(true);
    jf.setSize(100, 100);
    jf.addWindowListener(new WindowAdapter() {
      @Override
      public void windowClosing(WindowEvent e) {
        t.stopTimer();
      }
    });
    System.out.println("JFrameTest.main() DONE");
  }
}

class Timer extends Thread {
  boolean stop = false;

  @Override
  public void run() {
    for (int i = 0; i < 50; i++) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      if (stop)
        break;
      System.out.println("Counting :" + i);
    }
    System.out.println("Timer exit");
  }

  public void stopTimer() {
    stop = true;
  }
}
Gopi
I'd go one step further and use a `javax.swing.Timer` instead of a thread and call `stop()` on it in my `windowClosing(WindowEvent e)` method.
Qwerky
+1 sounds interesting i will try.
Lalchand
A: 

Your thread will keep running.

You need to either do as suggested by Gopi or you could use System.exit(0) in close operation of your JFrame.

NOTE: I am assuming here that Your application needs to end if this Frame is closed.

YoK
no i can't call the system.exit(0) it will close my application. i need to dispose the jframe and show a new jframe within a fraction of seconds.
Lalchand
A: 

Why not do one thing. Check that out yourself. You can either,

  • go to system processes, Or
  • you can update your Time thread to print in both places, i.e. Console and JLabel both.

Then you can easily find out the thing.

Adeel Ansari