0
我試圖做一個叫做ratsus的遊戲。它像國際象棋,但只與騎士。我對騎士atm的運動有問題。有時候,當我按下按鈕時,其他騎士出現的時候,它不應該(我不想這麼做)我很確定它與動作偵聽器有關的問題,即它的一次運行方法caballo不止一次。但我無法弄清楚。我很絕望,請幫助我。我對java很陌生。編程麻煩動作監聽器?
以下是我需要幫助的部分。
public void caballo(final int row, final int column) {
final JButton current = mesa[row][column];
current.setIcon(image);
panel.repaint();
acciones(row, column, current);
}
public void acciones(final int row, final int column, final JButton current) {
for (int i = 0; i < HEIGHT; i++) {
for (int j = 0; j < WIDTH; j++) {
mesa[i][j].addActionListener(e(row, column, current));
}
}
}
public ActionListener e(final int row, final int column,
final JButton current) {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (tienebotton(row + 2, column + 1)) {
if (e.getSource() == mesa[row + 2][column + 1]) {
current.setIcon(null);
caballo(row + 2, column + 1);
((AbstractButton) e.getSource()).setEnabled(false);
}
}
if (tienebotton(row + 2, column - 1)) {
if (e.getSource() == mesa[row + 2][column - 1]) {
current.setIcon(null);
caballo(row + 2, column - 1);
((AbstractButton) e.getSource()).setEnabled(false);
}
}
if (tienebotton(row - 2, column - 1)) {
if (e.getSource() == mesa[row - 2][column - 1]) {
current.setIcon(null);
caballo(row - 2, column - 1);
((AbstractButton) e.getSource()).setEnabled(false);
}
}
if (tienebotton(row - 2, column + 1)) {
if (e.getSource() == mesa[row - 2][column + 1]) {
current.setIcon(null);
caballo(row - 2, column + 1);
((AbstractButton) e.getSource()).setEnabled(false);
}
}
if (tienebotton(row + 1, column + 2)) {
if (e.getSource() == mesa[row + 1][column + 2]) {
current.setIcon(null);
caballo(row + 1, column + 2);
((AbstractButton) e.getSource()).setEnabled(false);
}
}
if (tienebotton(row - 1, column + 2)) {
if (e.getSource() == mesa[row - 1][column + 2]) {
current.setIcon(null);
caballo(row - 1, column + 2);
((AbstractButton) e.getSource()).setEnabled(false);
}
}
if (tienebotton(row + 1, column - 2)) {
if (e.getSource() == mesa[row + 1][column - 2]) {
current.setIcon(null);
caballo(row + 1, column - 2);
((AbstractButton) e.getSource()).setEnabled(false);
}
}
if (tienebotton(row - 1, column - 2)) {
if (e.getSource() == mesa[row - 1][column - 2]) {
current.setIcon(null);
caballo(row - 1, column - 2);
((AbstractButton) e.getSource()).setEnabled(false);
}
}
}
};
}
歡迎提供任何形式的建議。
這是tienebotton我把所以它並沒有給我數組索引越界的異常:
public boolean tienebotton(int row, int column) {
return (row >= 0 && row < HEIGHT && column >= 0 && column < WIDTH);
}
}
歡迎來到Stack Overflow!我建議你使用一個調試器或'System.out.println()'調用來驗證'caballo()'被調用了太多次。學習調試你的代碼是每個程序員的關鍵技能。 –
'tienebotton'做什麼?我想這個邏輯可以簡化。 – MaQy
就像在'acciones'中一樣,每當你做出一個動作時,你都會爲每個按鈕附加一個動作監聽器,這可能會導致當你點擊一個有效的位置時,那裏有一個騎士。 – Evans