這是我程序中類的片段(我刪除了一些不重要的代碼)。首先,程序總是調用方法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;
}
}
你的做法似乎過於複雜 - 你應該能夠只需要調用'e.getSource()'找出被點擊哪個球員。或者,也許我誤解了你想要做的事情。 – 2011-05-23 14:31:32
@jzd - 你明白我在做什麼,但也許我不明白getSource()方法:)當我在system.out中爲隨機播放器調用它時,我有這樣的東西:javax.swing.JLabel [ ,93,7,10x10,alignmentX = 0.0,alignmentY = 0.0 ......,所以93是coursorX,而7是coursorY。這正是我在代碼中所做的評論//很多代碼來搜索coursorX和coursorY。然後我必須找出哪個球員是這樣的,所以我打電話給findPlayer(coursorX,coursorY),將我上次設置的位置與當前的鼠標點擊進行比較。 – czy 2011-05-23 15:34:40
我想你的意思是向羅賓評論,而不是我。 – jzd 2011-05-23 15:39:06