Share this page 

Wake-up a Java appletTag(s): Javascript interaction


When moving the mouse over an image, we want to start an applet (here a simple chronometer), and when the mouse leave the image, the Applet should stop.

[JAVA APPLET]

import java.applet.*;
import java.awt.*;

public class JavaChrono extends Applet {
  String previousTime = "0" ;
  String currentTime  = "0";
  long j,k, l;
  boolean okToChrono = false;
  Color b, f;
  
  public void init() {
    b = getBackground();  
    f = getForeground();  
    MyThread tm = new MyThread(this); 
    tm.start();
    }

  public void startChrono() {
    j = System.currentTimeMillis();
    okToChrono = true;
    }
   
  public void stopChrono() {
    okToChrono = false;
    }
    
  public void paint(Graphics g) {
    if (okToChrono) {
      g.setColor(b);
      g.drawString(previousTime,10,30);    
      g.setColor(f);
      k = System.currentTimeMillis();
      l = k-j;
      currentTime = Long.toString(l/1000);
      g.drawString(currentTime,10,30);
      previousTime = currentTime;
      }
    }
  }

class MyThread extends Thread {
  JavaChrono theApplet;
  
  public MyThread(JavaChrono a) { 
    theApplet = a;      
    }

 public void run() {
   while (true) {
     try {
       theApplet.repaint();
       this.sleep(1000);
       }
     catch(InterruptedException e) { }
     }
   }
}

[HTML]

<HTML><HEAD></HEAD><BODY>
<APPLET CODE=JavaChrono.class 
        WIDTH=150 
        HEIGHT=150>
</APPLET>
<A HREF="" 
   onMouseOver="document.applets[0].startChrono()"
   onMouseOut="document.applets[0].stopChrono()"   >
   <IMG SRC="whatever.gif" WIDTH=100 HEIGHT=100>
</A>
</BODY></HTML>
Try it here.

In the next example, when we click on a FORM's button, we tell the applet to open or close a frame.

[HTML]

<HTML>
<HEAD></HEAD>
<BODY>
<APPLET NAME="myApplet" CODE="MyApplet.class" HEIGHT=1 WIDTH=1></APPLET>
<FORM>
<INPUT TYPE="button" 
 VALUE="Start the Applet" 
 onClick=
  "if (document.applets[0].isActive()) document.myApplet.showFrame()">
<INPUT TYPE="button" 
 VALUE="Stop the Applet" 
 onClick=
  "if (document.applets[0].isActive()) document.myApplet.disposeFrame()">    
</FORM></BODY></HTML>

[JAVA APPLET]

import java.applet.*;
import java.awt.*;

public class MyApplet extends Applet {
  Frame f = null;
  
  public void init() { }
  
  public void showFrame() {
    if (f == null) {
      f = new Frame();
      f.setSize(100,100);
      f.add(new Label("Hello World"));
      f.setVisible(true);
      }
    }
    
  public void disposeFrame() {
    if (f != null) {
      f.dispose(); 
      f = null;
      }
    }
}
Try it here.