Advertisement
public URL getCodeBase()
This method gives us the location of the directory in which our applet code file is located. This location is returned to us in terms of an object of URL class.
Using this object of URL class, we can get and load any image file present in the same directory using the next two methods. public Image getImage(URL url, String name)
This method gets the image file in the form of Image object. This image file named name is present in the directory location specified by url. This directory also contains the applet code. public drawImage(Image img, int x, int y, ImageObserver observer)
This method draws the image referred by Image object img, at the coordinates x and y in an applet's window.
We also need to pass an object of ImageObserver interface. We can do by passing this reference of our Applet class, because it implements ImageObserver interface.
//Evening handling in an applet
import java.awt.*;
import java.applet.*;
/*
<applet code="Applet3" width=400 height=350>
</applet>
*/
public class Applet3 extends Applet
{
Image im;
public void init()
{
System.out.println("initializing an applet");
System.out.println("The full path to our applet file : " + getDocumentBase());
System.out.println("Directory in which our applet file is located : " + getCodeBase());
im= getImage(getCodeBase(),"wood.jpg"); //loading an image from the same directory in which applet file is located
}
public void start()
{
System.out.println("Starting an applet");
}
public void stop()
{
System.out.println("Stopping an applet");
}
public void paint(Graphics g)
{
System.out.println("Painting the Applet");
g.drawString("Displaying an imagine in our applet", 0,10);
g.drawImage(im,50,50,this);
}
}
appletviewer Applet3.java
initializing an applet
The full path to our applet file : file:/D:/Java/Applet3.java
Directory in which our applet file is located : file:/D:/Java/
Starting an applet
Painting the Applet
Besides this, right after running the applet program using appletviewer a new applet window is displayed to us which contains our image- "wood.jpg" - Advertisement
import java.awt.*;
import java.applet.*;
/*
<applet code="Applet7" width=400 height=400>
</applet>
*/
public class Applet7 extends Applet
{
public void init()
{
System.out.println("initializing an applet");
}
public void paint(Graphics g)
{
System.out.println("Hello there");
g.drawString("Drawing an oval in our applet", 0,10);
g.drawOval(50,50,100,100); //draws an Oval in applet window
g.drawRect(150,150,100,100); //draws a Rectangle in applet window
g.drawLine(270,270,350,350); //draws a Line in applet window
}
}
appletviewer Applet7.java
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement