When I run my program, I need to add an image to my GUI during run time. As far as I know, getting the image from the source file works:
public ImageIcon getImage()
{
ImageIcon image = null;
if (length > 6.0)
{
//TODO
} else {
try
{
image = new ImageIcon(ImageIO.read( new File("car.png")));
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "An Error occured! Image not found.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
return image;
}
I then add the image to a JLabel
using the .setIcon()
method, but nothing changes on the GUI.
public void addCarImage(Car newCar, int spaceNo)
{
ImageIcon carImage;
carImage = newCar.getImage();
JOptionPane.showMessageDialog(null, "Car", "Car", JOptionPane.INFORMATION_MESSAGE, carImage);
carList[spaceNo - 1] = newCar;
carLabel[spaceNo - 1].setIcon(carImage);
}
The JOptionPane
message was added to see if the image will actually load, and it does.
Any ideas? I've used google to look for solutions, such as repaint()/revalidate()/updateUI()
and they didn't work.
Edit - carLabels
are added like so (before adding images). JLabels
are initially blank.
carLabel = new JLabel[12];
for (int i = 0; i < carLabel.length; i++)
{
carLabel[i] = new JLabel();
}
carPanel.setLayout(new GridLayout(3, 4));
for (int i = 0; i < 12; i++)
{
carPanel.add(carLabel[i]);
}