我正在尝试在Java中创建一个程序,它将逐个显示一组图像,以调整每个图像的大小。 我伸出的JPanel显示这样的图像:Java等待组件被绘制
public class ImagePanel extends JPanel{
String filename;
Image image;
boolean loaded = false;
ImagePanel(){}
ImagePanel(String filename){
loadImage(filename);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(image != null && loaded){
g.drawImage(image, 0, 0, this);
}else{
g.drawString("Image read error", 10, getHeight() - 10);
}
}
public void loadImage(String filename){
loaded = false;
ImageIcon icon = new ImageIcon(filename);
image = icon.getImage();
int w = image.getWidth(this);
int h = image.getHeight(this);
if(w != -1 && w != 0 && h != -1 && h != 0){
setPreferredSize(new Dimension(w, h));
loaded = true;
}else{
setPreferredSize(new Dimension(300, 300));
}
}
}
然后在事件线程我做的主要工作有:
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
createGUI();
}
});
在createGUI()我通过一组图像:
ImagePanel imgPan = new ImagePanel();
add(imgPan);
for(File file : files){
if(file.isFile()){
System.out.println(file.getAbsolutePath());
imgPan.loadImage(file.getAbsolutePath());
pack();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
问题是,我的程序没有调整大小p罗伯特,所以图像加载正确,但它不显示任何东西。 如果我只显示1张图片,它也可以用于最后一张图片。我认为问题是Thread.sleep()在图像绘制完成之前调用。
如何等待我的ImagePanel完成绘画并在此之后开始等待? 或者有另一种解决问题的方法吗?
谢谢! Leonty
谢谢!它使我走上正轨! 我现在在主线程中执行代码,所有操作现在都是同步的,所以等待绘画完成后才会发生。 – Leonti 2010-12-10 23:47:58