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.
…
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
getWidthand/orgetHeightis -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 passthis.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(...).