如何删除动作侦听器?

所以我正在制作一个国际象棋游戏,但只与骑士。

这是移动骑士的方法

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 = 0 && row = 0 && column < WIDTH); } } 

我的问题是,当我第一次出现新骑士时,我可以移动它。 所以我想也许如果我删除动作执行方法中的actionlistener我可以解决这个问题。 你怎么看? 如果这是一个愚蠢的问题,我很抱歉java

像nachokk说的那样,你应该使用: component.removeActionListener(theActionListenerYouWantToRemove)

以下是如何在您的e方法中使用它:

 public ActionListener e(final int row, final int column, final JButton current) { return new ActionListener() { public void actionPerformed(ActionEvent e) { current.setIcon(null); if (tienebotton(row + 2, column + 1)) { if (e.getSource() == mesa[row + 2][column + 1]) { caballo(row + 2, column + 1); } } if (tienebotton(row + 2, column - 1)) { if (e.getSource() == mesa[row + 2][column - 1]) { caballo(row + 2, column - 1); } } if (tienebotton(row - 2, column - 1)) { if (e.getSource() == mesa[row - 2][column - 1]) { caballo(row - 2, column - 1); } } if (tienebotton(row - 2, column + 1)) { if (e.getSource() == mesa[row - 2][column + 1]) { caballo(row - 2, column + 1); } } if (tienebotton(row + 1, column + 2)) { if (e.getSource() == mesa[row + 1][column + 2]) { caballo(row + 1, column + 2); } } if (tienebotton(row - 1, column + 2)) { if (e.getSource() == mesa[row - 1][column + 2]) { caballo(row - 1, column + 2); } } if (tienebotton(row + 1, column - 2)) { if (e.getSource() == mesa[row + 1][column - 2]) { caballo(row + 1, column - 2); } } if (tienebotton(row - 1, column - 2)) { if (e.getSource() == mesa[row - 1][column - 2]) { caballo(row - 1, column - 2); } } ((AbstractButton) e.getSource()).setEnabled(false); ((AbstractButton) e.getSource()).removeActionListener(this); } }; } 

我看到你是Java新手,你会发现我稍微修改了你的e方法只调用current.setIcon(null);((AbstractButton) e.getSource()).setEnabled(false); 我还确保删除动作侦听器只调用一次,你应该尽量避免编写重复的代码。