当我使用以下代码时:
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;
}
在我的 Java Applet 中,只有调用 repaint() (通过调整 Applet Viewer 窗口的大小),图像才会显示?为什么图片不显示?
最佳答案
必须这样处理异步加载的图像。
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();
}
}
异步读取图像时,getWidth(null)
将返回0,直到宽度确定等等。因此需要小心一点。
说明
加载图像被设计为异步完成。图像已经可用,但在读取之前,getWidth
和/或 getHeight
为 -1。您可以将 ImageObserver 传递给 getWidth/getHeight,然后在图像读取期间通知它。现在 JApplet 已经是一个 ImageObserver,所以你只需传递 this
即可。
读取代码将通过传递/注册的ImageObserver的方法imageUpdate来发出更改信号;宽度是已知的,有些(=不是全部),所以人们已经可以绘制预览,就像在 JPEG 像素化预览中一样。
这种异步技术是在早期需要慢速互联网的情况下使用的。
如果您想更简单地读取图像,请使用ImageIO.read(...)
。
关于java - 为什么我的图像不能显示在我的 Java Applet 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899663/