关于使用Java Swing在循环中动态加载图像的问题

public String[] imagesArray = {Images.firstImage, Images.secondImage}; String imagesPath = "/testproject/images/"; for(int i = 0; i<imagesArray.length; i++) { URL imageURL = this.getClass().getResource(imagesPath+imagesArray[i]); ImageIcon orignalImageIcon = new ImageIcon(imageURL); Image newImage = orignalImageIcon.getImage().getScaledInstance(100, 90, java.awt.Image.SCALE_SMOOTH); ImageIcon newImageIcon = new ImageIcon(newImage); JButton receiptButton = new JButton(newImageIcon); receiptButton.setBorder((new EmptyBorder(0,0,0,0))); toolBar.add(receiptButton); add(toolBar); } 

我的设计布局中没有显示图像?

问题很可能是使用ImageIcon加载原始图像的异步加载特性。

如果那是问题:

  1. 有一种简单的方法来测试它。 将orignalImageIcon添加到按钮,看看它们是否全部显示。
  2. 有一种简单的方法可以解决它。 使用ImageIO.read(URL)加载图像 – 一种将阻塞直到图像完全加载的方法。