关于使用Java Swing在循环中动态加载图像的问题 [英] Issue regarding dynamically loading Images in loop using Java Swing

查看:300
本文介绍了关于使用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 加载原始图像的异步加载特性。 / p>

如果这是问题:


  1. 有一种简单的方法可以测试它。将 orignalImageIcon 添加到该按钮,看看它们是否全部显示。

  2. 有一种简单的方法可以解决它。使用 ImageIO.read(URL)加载图像 - 一种将阻塞图像直到图像完全加载的方法。


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);
    }

Images not shown in my design layout?

解决方案

The problem is most likely the asynchronous loading nature of using an ImageIcon to load the original images.

If that is the problem:

  1. There is an easy way to test it. Add the orignalImageIcon to the button and see if they all appear.
  2. There is an easy way to fix it. Load the images using ImageIO.read(URL) - a method that will block until the image is completely loaded.

这篇关于关于使用Java Swing在循环中动态加载图像的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆