Faizan Ahmed
Faizan Ahmed

Reputation: 93

Issue regarding dynamically loading Images in loop using 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);
    }

Images not shown in my design layout?

Upvotes: 2

Views: 444

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168815

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.

Upvotes: 4

Related Questions