I have created a program to add an ImageIcon to the next empty JLabel, the compiler shows no errors so why isn't this working? The setEmptySpace contains a loop that returns an empty space and the getCar method is supposed to set the icon.
package CarPark;
//add imports
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Park extends JPanel
{
//declare a JLabel array for parking space
JLabel[] parkingSpace;
//declare ImageIcon class for cars
ImageIcon car;
public Park()
{
//create a new instance of the parking space array with 12 spaces
parkingSpace = new JLabel[12];
//populate array
for (int i = 0; i < parkingSpace.length; i++)
{
//create parking space JLabels
//parkingSpace[i] = new JLabel(String.valueOf(i + 1));
parkingSpace[i] = new JLabel();
//set parking space colour
parkingSpace[i].setBackground(new Color(85, 55, 170));
//make JLabels opaque
parkingSpace[i].setOpaque(true);
}
//create grid for parking space setting rows, columns, horizontal gap and vertical gap
this.setLayout(new GridLayout(4, 3, 4, 4));
//set background colour to white
this.setBackground(new Color(255, 255, 255));
//add 12 parking spaces to panel
for (int i = 0; i < 12; i++)
{
this.add(parkingSpace[i]);
//create a red border with a thickness of 4 pixels
parkingSpace[i].setBorder(BorderFactory.createLineBorder(Color.RED, 4));
}
}
//find an empty parking space
int setEmptySpace()
{
for(int i = 0; i < parkingSpace.length; i++)
{
if(parkingSpace[i] == null)
{
return i;
}
}
return -1;
}
//add car image to empty parking space
void getCar(int getEmptySpace)
{
car = new ImageIcon("car.png");
parkingSpace[getEmptySpace].setIcon(car);
}
}