我创建了一个将ImageIcon添加到下一个空JLabel的程序,编译器显示没有错误,为什么这不起作用? setEmptySpace包含一个返回空格的循环,并且getCar方法应该设置图标。如何将ImageIcon设置为JLabel数组?
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);
}
}
欢迎来到SO。你在哪里使用'getCar'? – c0der
1)为了更快地获得更好的帮助,请发布[MCVE]或[简短,独立,正确的示例](http://www.sscce.org/)。 2)获取图像的一种方法是通过[本问答](http://stackoverflow.com/q/19209650/418556)中的图像进行热链接。 –
我在使用类协作连接的不同类中的动作侦听器中使用getCar。到目前为止,我只连接了getCar方法,它看起来像我需要连接setEmptySpace以及它需要一个整数。我必须稍后再做。 – Nebula