Search code examples
javaswingloopsfinal

How do I solve local referenced variables inside a for loop?


I'm writing a Swing application and trying to make a menu where each menu item has its own action:

Here's how I wanted to solve this:

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);
    }
}

However, I cannot use loadGame(i), because it says i would have to be final. I understand the reason for this, but I do not know how to work my way around it.


Solution

  • Quick trick: define a final variable at each iteration of the loop that takes the (non final) value of i and use it:

    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);
      }
    }