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