简体   繁体   中英

Why won't my image display in my Java Applet?

When I use the following code:

    public void paint(Graphics g){

    //Displays version number and name.
    g.setFont(new Font("Courier", Font.PLAIN, 10));
    g.drawString("DCoder " + execute.Execute.version, 2, 10);

    //Displays logo in center.
    g.drawImage(logo, centerAlign(logo.getWidth(null)), 50, this);


}

private int width(){
    //Gets and returns width of applet.
    int width = getSize().width;
    return width;
}
private int height(){
    //Gets and returns height of applet.
    int height = getSize().height;
    return height;
}

private int centerAlign(int obWidth){
    int align = (width()-obWidth)/2;
    return align;
}

in my Java Applet, the image will not display until I call repaint() (by resizing the Applet Viewer window)? Why won't the image display?

An asynchronous loaded image has to be handled thus.

logo.getWidth(this); // Indicate asynchronous ImageObserver

...

@Override
public boolean imageUpdate(Image img,
              int infoflags,
              int x,
              int y,
              int width,
              int height) {
    if ((infoflags & ImageObserver.ALLBITS) == ImageObserver.ALLBITS) {
        // The image is entirely read.
        repaint();
    }
}

When asynchronous reading an image, getWidth(null) will return 0 till the width is determined etcetera. Therefore one needs to be a bit careful.


Explanation

Loading images was designed to be done asynchronously. The Image is already available, but before being read getWidth and/or getHeight is -1. You can pass an ImageObserver to getWidth/getHeight, which is then notified during the image reading. Now JApplet already is an ImageObserver, so you can just pass this .

The reading code will the passed/registered ImageObserver's method imageUpdate to signal a change; that the width is known, that SOMEBITS (= not all), so one could already draw a preview, like in a JPEG pixelized preview.

This asynchrone technique was in the earlier days of the slow internet needed.

If you want to read an image simpler, use ImageIO.read(...) .

Why won't the image display?

Most probably because it was loaded using an asynchronous method.

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