Simulate a "mouse over" event to toggle an imageTag(s): AWT


Use a special Canvas to preload 2 GIFs, and using a MouseListener simply toggle the image.

[JDK1.1]
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class ToggleGifCanvas extends Canvas
  implements MouseListener {
  Image img1, img2;
  int     index = 0;
  MediaTracker tracker;

  public ToggleGifCanvas(URL n1, URL n2) {
    tracker = new MediaTracker(this);
    try {
      img1 = Toolkit.getDefaultToolkit().getImage(n1);
      img2 = Toolkit.getDefaultToolkit().getImage(n2);
      tracker.addImage(img1,0);
      tracker.addImage(img2,1);
      tracker.waitForAll();
      addMouseListener(this);
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void paint(Graphics g) {
    if (img1 != null) {
       if (index == 0) {
          g.drawImage(img1,0,0,this);
          index++;
       }
       else {
          g.drawImage(img2,0,0,this);
          index--;
       }
    }
  }

  public Dimension getPreferredSize (){
    return new Dimension
      (img1.getHeight(this), img2.getWidth(this));
  }

  public void mouseClicked(MouseEvent e) {}
  public void mousePressed(MouseEvent e) {}
  public void mouseReleased(MouseEvent e) {}
  public void mouseEntered(MouseEvent e) {
    index = 1;
    repaint();
  }
  public void mouseExited(MouseEvent e) {
    index = 0;
    repaint();
  }
}
To use such Canvas, try something like this. This example needs our Gumby GIFs ( and ).
import java.applet.*;
import java.awt.*;
import java.net.*;

public class TestToogleGifCanvas extends Applet {
  ToggleGifCanvas tgc;

  public void init() {
     try {
       tgc = new ToggleGifCanvas
           (new URL(getDocumentBase(),"images/gumby.gif"),
            new URL(getDocumentBase(),"images/gumby2.gif"));
       add(tgc);
       }
     catch (Exception e) {
       e.printStackTrace();
       }
    }
}
Try it here.
blog comments powered by Disqus