I want to know, how to keep a method running in the background. ie. this method starts when the program starts and keeps executing its statements until the program is closed
"SWING isn't thread safe" as you may have seen in may of the Java Docs.
Best way is to use a SwingWorker class. It provides functionality for calculation of results or performance of tasks that have long execution times.
In the simplest way, you could have something like this:
import javax.swing.JFrame;
public class TestBackgroudMethod {
public static void main(final String[] args) {
MyBackgroudMethod thread = new MyBackgroudMethod();
thread.setDaemon(true);
thread.start();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame jFrame = new JFrame();
jFrame.setSize(200, 200);
jFrame.setVisible(true);
}
});
}
public static class MyBackgroudMethod extends Thread {
@Override
public void run() {
while (true) {
System.out.println("Executed!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
Edit
Added sample with swing worker:
import javax.swing.JFrame;
import javax.swing.SwingWorker;
public class TestBackgroudMethod {
public static void main(final String[] args) {
new SwingBackgroupWorker().execute();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame jFrame = new JFrame();
jFrame.setSize(200, 200);
jFrame.setVisible(true);
}
});
}
public static class SwingBackgroupWorker extends SwingWorker<Object, Object> {
@Override
protected Object doInBackground() throws Exception {
while (true) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
System.out.println("executed");
// here the swing update
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}