Execute a method at a specified time intervalTag(s): Thread
In the following example, we are using a special class, DelayedMethod, which extends the Thread class. This Thread will receive a pointer to the "parent class" in its constructor. This pointer will be used to call a know method at a specified interval.
import java.applet.*; import java.awt.*; import java.awt.event.*; import java.net.*; public class AnnoyingPopUps extends Applet implements ActionListener { Button b1, b2; DelayedMethod dm; int x = 0; public void init() { b1 = new Button("Start Annoying Popops"); b2 = new Button("Stop Annoying Popops"); add(b1); add(b2); b1.addActionListener(this);b2.addActionListener(this); dm = new DelayedMethod(this, 1000); // 1 second dm.start(); } public void actionPerformed(ActionEvent ae) { if (ae.getSource() == b1) { dm.oktorun = true; } else if(ae.getSource() == b2) { dm.oktorun = false; }s } public void displayPopup() { SimplePopUp d = new SimplePopUp(); d.show(); d.setLocation(x , x); x = x + 5; } class SimplePopUp extends Dialog { SimplePopUp() { super(new Frame(), "annoying popup"); this.addWindowListener (new WindowAdapter() { public void windowClosing(WindowEvent e) { e.getWindow().dispose(); } } ); } } class DelayedMethod extends Thread { AnnoyingPopUps myObj = null; // customize for your need boolean oktorun = false; int delay; DelayedMethod(AnnoyingPopUps myObj) { this.myObj = myObj; this.delay = 2000; } DelayedMethod(AnnoyingPopUps myObj, int delay) { this.myObj = myObj; this.delay = delay; } public void run() { while (true) { try { sleep(delay); if (oktorun) myObj.displayPopup(); // customize this too! } catch (InterruptedException ignored) {} } } } }
NOTE: Check this How-to to achieve to same goal by using the Timer object.
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com