这是程序中类的片段(我删除了一些不重要的代码)。首先,程序始终调用firstSet()
方法,该方法将JPanel(面板)上的所有JLabel(播放器)设置为。然后,当我单击JLabel时,mouseClicked()
运行方法findPlayer()
,因此我知道选择了哪个JLabel。到目前为止,一切正常。
问题开始于我开始仿真-方法simulationStart()
运行10次。此后,当我单击播放器时,cmd行显示:I can't find it :(
。我写了一些system.out来找出问题所在。问题出在locationX
和locationY
字段中,我不知道为什么它们在findPlayer()
和simulationStart()
中不同。
public class setBoard extends JFrame implements MouseListener {
int[] locationX = new int[100];
int[] locationY = new int[100];
public void setLocation() {
for (int i = 0; i < 100; i++) {
locationX[i] = (int) (random() * (sizeX - xy));
locationY[i] = (int) (random() * (sizeY - xy));
}
}
public ArrayList<JLabel> firstSet() {
setLocation();
for (int i = 0; i < 100; i++) {
player = new JLabel();
//
//some code to JLabel set
//
playerList.add(player);
player.setBounds(locationX[i], locationY[i]);
player.addMouseListener(this);
}
return playerList;
}
public ArrayList<JLabel> simulationStart(ArrayList<JLabel> playerList) {
this.playerList = playerList;
setLocation();
for (int i = 0; i < 100; i++) {
playerList.get(i).setBounds(locationX[i], locationY[i]);
playerList.add(playerList.get(i));
}
return playerList;
}
public void mouseClicked(MouseEvent e) {
//
//a lot of code to search coursorX and coursorY, this works good
//
//if left mouse button
if (e.getButton() == 1) {
final int playerNr = findPlayer(coursorX, coursorY);
if (playerNr == -1) {
System.out.println("I can`t find it :( ");
}
else{
//
//code to do when it find player
//
}
}
}
//
//
//
private int findPlayer(int x, int y) {
int playerNr = -1;
for (int i = 0; i < 100; i++) {
if (x == locationX[i] && y == locationY[i]) {
playerNr = i;
}
}
return playerNr;
}
}
最佳答案
每当您呼叫simulationStart
时,您就会再次将玩家添加到playerList中。因此,播放器的数量超过了100。为什么不尝试打印出playerList的大小并检查它是否符合您的期望?
我认为您可能需要删除以下语句:playerList.add(playerList.get(i));