Ptrikl957:
私が書いているのSwingアプリケーションを、各メニューにしようとしたメニュー項目は、自身の持っているアクションを:
ここで私はこの問題を解決したかった方法は次のとおりです。
private void createGameLevelMenuItems(JMenu menu){
for (int i = 0; i<10; i++) {
JMenuItem item = new JMenuItem(new AbstractAction("Level-" + i) {
@Override
public void actionPerformed(ActionEvent e) {
game.loadGame(i);
board.refresh();
pack();
}
});
menu.add(item);
}
}
しかし、私が使用することはできませんloadGame(i)
、それは言うので、i
最終的でなければならないであろう。私はその理由を理解し、私はそれのまわりで私のように動作するのか分かりません。
ブルーノ:
クイックトリック:の(非最終)値をとるループの各反復で、最終的な変数を定義i
し、それを使用します。
private void createGameLevelMenuItems(JMenu menu){
for (int i = 0; i<10; i++) {
final int j = i; // <--- this line do the thing
JMenuItem item = new JMenuItem(new AbstractAction("Level-" + j) {
@Override
public void actionPerformed(ActionEvent e) {
game.loadGame(j);
board.refresh();
pack();
}
});
menu.add(item);
}
}