[5998] in java-interest

home help back first fref pref prev next nref lref last post

Re: loading image into Canvas

daemon@ATHENA.MIT.EDU (David Geary)
Fri Mar 8 00:25:46 1996

Date: Wed, 6 Mar 1996 17:49:04 -0700
From: David.Geary@Central.Sun.COM (David Geary)
To: ra104@cosc.Sun.COM, java-interest@java.Eng.Sun.COM

> Java Group,

  I'm not the Java Group, but perhaps I can be of assistance.

> I noticed that I can easily load an image into a applet, but
> how do I load it into a Canvas?  I have a frame created that I 
> want to put an image into.  
> 
> I noticed that getImage can only be called if you inherit from 
> Applet, AppletContext, or Tookit --- not Canvas.

  You need not inherit from Toolkit to create an Image.

  You can get ahold of the default toolkit from any method in any class,
by calling Toolkit.getDefaultToolkit().

  Any class derived from Component can call getToolkit() to, well, to
get the toolkit.

  I've included some code below that will display an image.  Note that
you must provide the .gif file.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 David Geary                                   "You cannot convince me
 geary@rmtc.Central.Sun.COM                     I won't buy your bag of goods" 
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/* Run as:  java testWithMediaTracker

	As long as the gif file specified in ImageTestCanvas() is in
	the current directory it should be displayed
*/
import java.awt.*;

public class testWithMediaTracker extends Frame {
	testWithMediaTracker() {
		super("Image Test");
		addMenu();
	}
 	static public void main(String args[]) {
		Frame frame = new testWithMediaTracker();

		ImageTestCanvas canvas = new ImageTestCanvas();
		frame.add("Center", canvas);
		frame.reshape(100,100,300,300);
		frame.show();
  	}
  	private void addMenu() {
	  MenuBar mbar = new MenuBar();
	  Menu    filemenu = new Menu("File");

	  filemenu.add("quit");
	  mbar.add(filemenu);
	  setMenuBar(mbar);
  	}
  	public boolean handleEvent(Event event) {
	  if(event.target instanceof MenuItem)
		System.exit(0);

	  return false;
  	}
}

class ImageTestCanvas extends Canvas {
 	private Image im;

	public ImageTestCanvas() {
		MediaTracker tracker = new MediaTracker(this);

		im = getToolkit().getImage("user.gif");
		tracker.addImage(im, 0);

		try                           tracker.waitForID(0);
		catch(InterruptedException e) System.out.println("Interrupted!");
	}
	public void paint(Graphics g) {
	  g.drawImage(im,10,10,this);
	}
}

-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com

home help back first fref pref prev next nref lref last post