Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Applets
Expertise: Beginner
Mar 21, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Setting Cursor in Applet Code in Browser Window

The AWT's Frame class provides a setCursor method that allows me to set the cursor to one of the standard images (arrow, watch, etc.). The problem is I'm implementing an applet that lives in a browser window, not in a frame. How can I set the cursor in applet code (short of creating an invisible frame and calling its setCursor method)?

I recently read somewhere that one can simply search through the ancestors of an applet in its component hierarchy until a frame is encountered, then use the frame's setCursor() method. I was surprised. I guess this frame must be the one created by the browser itself. I tried a few experiments and discovered that in Netscape my applet did indeed have an ancestral container which was an instance of a class called EmbeddedAppletFrame, which extended the Frame class.

Using Sun's Applet Viewer, the same experiment produced an ancestor in the AppletViewer class, which apparently extends the Frame class. If it is generally true that all applets in all browsers are contained in a Java frame, then this seems to open the door for all kinds of interesting hacks!

Below is a sample applet that allows users to select a cursor. It works in Netscape and Applet Viewer.


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

public class CursorDemo extends Applet {

   private Frame myFrame;  // my frame ancestor

   public void init() {

      Panel p = new Panel();
      p.setLayout(new FlowLayout());
      p.add(new Button("CROSSHAIR"));
      p.add(new Button("HAND"));
      p.add(new Button("WAIT"));
      p.add(new Button("TEXT"));
      p.add(new Button("DEFAULT"));

      setLayout(new BorderLayout());
      add("North", new Label("Select a cursor:"));
      add("Center", p);

      /* search ancestors in the component hierarchy
         until a frame is found
      Object parent = getParent();
      while (! (parent instanceof Frame)) 
         parent = ((Component) parent).getParent ();
      myFrame = (Frame) parent; // EmbeddedAppletFrame in Netscape

   public boolean action(Event e, Object arg) {
      if (arg.equals("CROSSHAIR"))
         myFrame.setCursor (Frame.CROSSHAIR_CURSOR);
      else if (arg.equals("HAND"))
      else if (arg.equals("WAIT"))
      else if (arg.equals("TEXT"))
      else if (arg.equals("DEFAULT"))
         return false;
      return true;

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date