|
Images in the main class (the applet) are easy; see here.
If you are putting them in one of your classes that get called
by the applet (or JFrame), its just a little trickier. The class that is used
needs to know about that window (called a component).
For example if we had an applet class called Main and a Spaceship
class.
In Main when we declare the Spaceship we might:
Spaceship theSpaceship = new SpaceShip(x,y,this);
We have added the word this -> which is referring to this applet.
Now the Spaceship (which had parameters x,y) will take in a parameter
that is the applet.
In Spaceship our constructor looks like:
//Globals to keep track of the image and the applet
Image img;
Component window; //this window could be either a JFrame or JApplet
public Spaceship(int x, int y, Component window)
{
this.window=window;
//Now I will load the img
img = window.getToolkit().getImage(getClass().getResource("liftoff.jpg"));
}
For our drawing method: we need to draw on the window
public void draw(Graphics g)
{
g.drawImage(img,200,200,window);
}
Now in
Here is an example:
The Main class:
import java.applet.*;
import java.awt.*;
public class Main extends Applet
{
Spaceship theSpaceship;
public void init()
{
theSpaceship = new SpaceShip(x,y,this);
}
public void paint (Graphics g)
{
theSpaceship.draw(g);
}
}
The Spaceship class:
import java.awt.*;
public class Spaceship
{
//Globals to keep track of the image and the applet
Image img;
Component window; //this window could be either a JFrame or JApplet
public Spaceship(int x, int y, Component window)
{
this.window=window;
//Now I will load the img
img = window.getToolkit().getImage(getClass().getResource("liftoff.jpg"));
}
public void draw(Graphics g)
{
g.drawImage(img,200,200,window);
}
}
|