チェス盤の個々のタイルとしてJButtonを使用して小さなチェスゲームを作成しています。私は、次のコードを使用して、各タイル(計64)アクションリスナーを与える:Java - 自己のインスタンスをActionListenersに渡す
for (int y = 0; y < chessBoardColumns; y++) {
for (int x = 0; x < chessBoardRows; x++) {
JButton square = new JButton();
ActionListener squareListener = new ChessSquareListener(this);
chessBoardSquares[x][y] = square;
chessBoardSquares[x][y].addActionListener(squareListener);
}
}
アクションリスナーが別のパッケージであり、次のようになります。あなたのよう
public class ChessSquareListener implements ActionListener {
private ChessGame game;
public ChessSquareListener(ChessGame game) {
this.game = game;
}
public void actionPerformed(ActionEvent e) {
game.doSomething();
}
}
私はゲーム全体のインスタンスを各四角形のリスナーに渡しています。これは各リスナーのためにゲームの64コピーを作成するのだろうか、それとも単にゲームインスタンスへの参照を渡すだけですか?
ゲームの64個のコピーではなく、ゲームインスタンスへの参照を渡す – prasad