Jade
Jade

Reputation: 71

How to draw an image on the applet

public class ImageExample2 extends Applet
{

    BufferedImage bi;


    public void init ()
    {

        resize (500, 500);

        try
        {

            BufferedImage bi = ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));
        }
        catch (java.io.IOException e)
        {
            e.printStackTrace ();
        }
    }


    public void paint (Graphics g)
    {

        g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);

    }
}

Everytime I try to run it, it gives me a null pointer exception. How can I fix it?

Upvotes: 0

Views: 745

Answers (2)

Java42
Java42

Reputation: 7706

Change:

BufferedImage bi=ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));

to

bi = ImageIO.read (new File ("G:\\Java\\WhatDotColour\\Pacman.PNG"));

and change

g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);

to

if (bi!=null) g.drawImage (bi, 20, 140, this); //.drawImage(in, 0, 0, null);

Upvotes: 0

Braj
Braj

Reputation: 46841

Don't mix Applet with File. They are just like oil & water. Applet runs in the browser. Always use relative path.

Use Applet#getCodeBase() to gets the base URL. This is the URL of the directory which contains this applet.

Sample code: (look at the output of getCodeBase() method and modify the image path)

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;

public class ImageExample2 extends Applet {

    private Image bi;

    public void init() {

        resize(500, 500);

        System.out.println(getCodeBase()); // file:/D:/Workspace/JavaProject/bin/

        // This the actual code that should be used to read the image in Applet
        bi = getImage(getCodeBase(), "images/222.png");
    }

    public void paint(Graphics g) {
        g.drawImage(bi, 20, 140, this);

    }
}

If you are using Windows & Eclipse IDE then look at the screenshot shown below for above sample code image path.

enter image description here

Upvotes: 1

Related Questions