这是我程序中的类的片段(我删除了一些不重要的代码)。首先,程序总是调用方法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;
}
}
答案 0 :(得分:1)
每当你致电simulationStart
时,你都会再次向playerList添加玩家。所以玩家数量超过100个。为什么不尝试打印出playerList的大小并检查它是否符合您的期望?
我认为您可能需要删除声明:playerList.add(playerList.get(i));