Haveing problem with my JMenuItem and ActionListener, I'm trying to make a JMenuItem that can select numbers of players in a game but my PlayerAlt[i].addActionListener(players);
code gives me an error that "players cannot be resolved to a variable"
String[] Players = { "1", "2", "3", "4" };
JMenu pmenu = new JMenu("Players");
final JMenuItem[] PlayerAlt = new JMenuItem[Players.length];
for (int i = 0; i < PlayerAlt.length; i++) {
PlayerAlt[i] = new JMenuItem(Players[i]);
pmenu.add(PlayerAlt[i]);
PlayerAlt[i].addActionListener(players);
}
ActionListener players = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < PlayerAlt.length; i++) {
if (e.getSource() == PlayerAlt[i]) {
Gamerside.add(s1);
}
}
}
};
The variable
players
is declared after you want to use it. Thus it can not be resolved.Move the
players
declaration above the loop