简体   繁体   中英

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?

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");

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM