InspiringProgramming
InspiringProgramming

Reputation: 267

Loading an Image using getImage

Here is a simple applet to try loading an image but it shows a blank window

import java.applet.*;
import java.awt.*;

public class Mama extends Applet {

int width, height;
Image img;

@Override
public void init(){
    img = getImage(getCodeBase(), "C:\\Users\\......\\Backgound.png");
}

@Override 
public void paint(Graphics g){
    g.drawImage(img, 0, 0, this);
  }
}

I copied the path of the image from the directory, what am I doing wrong?

Upvotes: 1

Views: 19049

Answers (2)

Daniyar Myrzakanov
Daniyar Myrzakanov

Reputation: 50

You can write as here

import java.applet.Applet;
import java.awt.*;
import java.net.URL;

public class SimpleImageLoad extends Applet {
    Image img;

    @Override
    public void init() {
        super.init();
        img=getImage(getCodeBase(),"file:\\D:\\pic.PNG");
        System.out.println(getCodeBase());
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        g.drawImage(img,0,0,this);
    }
}

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

Unless they are signed, applets can only read files from the same location from which they were loaded. Move the image to image to a location that is accessible relative to the class (or document) path and use:

img = getImage(getCodeBase(), "Backgound.png");

Upvotes: 4

Related Questions