Reputation: 141
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);
}
}
Upvotes: 1
Views: 597
Reputation: 347332
I would take a really long, hard look at this line...
for (int i = 0; i > 30; i++) {
As Adam Savage would say, "well, there's your problem".
Personally, I would use ImageIO
over Toolkit.getImage
, unless you have a really good reason not to (like you need the background loading capabilities of Toolkit.getImage
due to slow network connection). ImageIO
will 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...
try {
wallpaper = ImageIO.read(getClass().getResource("images/wallpaper.jpg"));
for (int i = 0; i < 30; i++) {
teamsImg[i] = ImageIO.read(getClass().getResource("images/img.png"));
}
} catch (IOException iOException) {
System.err.println("Bad things happened");
iOException.printStackTrace();
}
This will require to use Image
instead of ImageIcon
to 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)
Upvotes: 3