This is fragment of class in my program (I deleted some not important code). At First, program always calls method firstSet()
which sets all JLabels(players) on JPanel(board). Then when I click on JLabel, mouseClicked()
runs method findPlayer()
, so I know which JLabel whose chose. To this moment everything is OK.
Problem begins when I 开发者_如何学运维start simulation - method simulationStart()
run 10 times. After this when I click player, cmd line shows: I can't find it :(
. I wrote some system.out to find out what is wrong. Problem is in fields locationX
and locationY
, I don't know why they are different in findPlayer()
and 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;
}
}
Whenever you call simulationStart
you are adding players to the playerList again. So the number of players goes above 100. Why don't you try printing out the size of playerList and check if it is what you expect?
I think you may need to remove the statement: playerList.add(playerList.get(i));
精彩评论