我正在尝试用Java创建一个程序,该程序将一个接一个地显示一组图像,并调整每个图像的框架大小。我正在扩展 JPanel 以显示这样的图像:
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();
}
}
}
问题是我的程序正确地调整了大小,所以图像被正确加载但它不显示任何东西。如果我只显示一张图像,它也适用于最后一张图像。我认为问题是在图像绘制完成之前调用了 Thread.sleep() 。
我怎样才能等待我的 ImagePanel 完成绘画并在那之后开始等待?还是有其他方法可以解决问题?
谢谢!莱昂蒂