Reputation: 651
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?
Upvotes: 0
Views: 724
Reputation: 109613
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(...)
.
Upvotes: 2
Reputation: 168845
Why won't the image display?
Most probably because it was loaded using an asynchronous method.
Upvotes: 1