A Canvas with Class


To refer to another class in the same source file, simply include the

runnable class file in the same directory as an image file, whose name

you specify in line 6 below (or, include a path or complete URL in the

file reference).

What's going on? The program actually contains two classes, one

(modifiedCanvas) in the same file as another (ModCanvas). The class

modifiedCanvas extends the Canvas class, which the java.awt package

contains. There's one constructor established in modifiedCanvas -- one

that calls for an Image object as an argument. That class paints the

specified Image object onto itself.

The public class (which is to say, ModCanvas) creates an instance of

the modifiedCanvas class by calling its single constructor with an

Image object retrieved via the getImage() method of the windowing

toolkit. That instance of modifiedCanvas is then added to the Frame

called demoFrame, which is finally made visible.

Here's the code:

import java.awt.*;

public class ModCanvas {

static public void main(String a[]) {

Toolkit t = Toolkit.getDefaultToolkit();

Image someImage = t.getImage("someimage.jpg");

Frame demoFrame = new Frame("A Frame with a Modified Canvas in


modifiedCanvas mc = new modifiedCanvas(someImage);






class modifiedCanvas extends Canvas {

Image savedImage;

public modifiedCanvas(Image someImage) {


savedImage = someImage;


public void paint(Graphics g){

g.drawImage(savedImage, 10, 10, this);



Free Course: JavaScript: The Good Parts
View Comments
You Might Like
Join the discussion
Be the first to comment on this article. Our Commenting Policies