Это фрагмент класса в моей программе (я удалил не очень важный код). Сначала программа всегда вызывает метод firstSet()
, который устанавливает все JLabels (игроки) на JPanel (доска). Затем, когда я нажимаю на 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;
}
}