【发布时间】:2017-04-08 09:56:38
【问题描述】:
我已经创建了一个将 ImageIcon 添加到下一个空 JLabel 的程序,编译器没有显示错误,为什么这不起作用? setEmptySpace 包含一个返回空白空间的循环,并且 getCar 方法应该设置图标。
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? -
1) 为了尽快获得更好的帮助,请发帖 minimal reproducible example 或 Short, Self Contained, Correct Example。 2) 例如,获取图像的一种方法是热链接到在this Q&A 中看到的图像。
-
我正在使用类协作连接的另一个类中的动作侦听器中使用 getCar。到目前为止,我只连接了 getCar 方法,看起来我需要连接 setEmptySpace 并且它需要一个整数。稍后我将不得不这样做。
-
我正在尝试使用 refCar.getCar(refCar.setEmptySpace());在另一个类中作为引用变量传递,但它们似乎在 actionPerformed 方法中不起作用,给我一个空指针异常。为什么会这样,我该如何解决?
标签: java arrays swing label imageicon