Lalchand
Lalchand

Reputation: 7827

java swing thread problem

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.

Upvotes: 1

Views: 1184

Answers (2)

Gopi
Gopi

Reputation: 10293

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;
  }
}

Upvotes: 2

YoK
YoK

Reputation: 14505

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.

Upvotes: 0

Related Questions