JMenuItem和ActionListener

时间:2013-12-06 11:43:59

标签: java swing actionlistener jmenuitem

我的JMenuItem和ActionListener出现了问题,我正在尝试制作一个可以在游戏中选择多个玩家的JMenuItem,但是我的PlayerAlt[i].addActionListener(players);代码会给我一个错误,即“玩家无法解析为变量”

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

2 个答案:

答案 0 :(得分:1)

在您想要使用它之后声明变量players。因此无法解决。

players声明移到循环上方

ActionListener players = new ActionListener() {
      ......
};
for (int i = 0; i < PlayerAlt.length; i++) {
    .....
    PlayerAlt[i].addActionListener(players);
}

答案 1 :(得分:0)

在您的示例中,{/ 1}}在之后声明为,您尝试使用它(稍后两行),因此在您尝试使用它时它不存在。

澄清:

players