I have 30 ImageIcons that I have declared in a ImageIcon array. I have declared them all using a FOR loop. THe only problem is that when I try to add the ImageIcon to a JLabel and display the JPanel on the screen, it doesn’t work.Here is my code:
package screens;
import javax.swing.*;
import java.awt.*;
public class gameScreen extends JPanel {
private static final long serialVersionUID = 1L;
// -------------VARIABLES---------------//
Image wallpaper = (Image)Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/wallpaper.jpg"));
ImageIcon[] teamsImg = new ImageIcon[30];
public gameScreen() {
for(int i = 0;i>30;i++){
teamsImg[i] = new ImageIcon(Toolkit.getDefaultToolkit().getImage(
getClass().getResource("images/img.png")));
}
JLabel label = new JLabel(teamsImg[27]);
add(label);
}
// -------------PAINT FUNCTION----------//
public void paintComponent(Graphics g) {
g.drawImage(wallpaper,0,0,null);
}
}
I would take a really long, hard look at this line…
As Adam Savage would say, “well, there’s your problem”.
Personally, I would use
ImageIOoverToolkit.getImage, unless you have a really good reason not to (like you need the background loading capabilities ofToolkit.getImagedue to slow network connection).ImageIOwill give you access to a much wider range of possible image formats, thanks to it’s plugin architecture as well as guarantee that when it returns, the image will fully loaded.Something like…
This will require to use
Imageinstead ofImageIconto store the images, but it’s a little sacrifice for the benefit it brings you.Also, you do know, you’re loading the same image over and over again??? You could just load it once and set the reference to each element in the array, it’s effectively the same thing…(as I understand it, the image API is using a cached version to make repeated loads quicker)