【问题标题】:Calling Enclosing Class methods inside Inner Class在内部类中调用封闭类方法
【发布时间】:2012-11-13 15:10:53
【问题描述】:

我在内部类中调用封闭类方法,但出现语法错误。代码如下:

public class Horizon
{
  ....
  public void checkWinner()
  {
    if(x[1]==1 && x[2]==1 && x[3]==1 || x[4]==1 && x[5]==1 && x[6]==1 || x[7]==1 && x[8]==1 && x[9]==1)
    {
      JOptionPane.showMessageDialog(null, "Congratulations!\n      Player 1 won!", "Congratulations",JOptionPane.OK_OPTION);
    }
  }
  private class HandlerClass implements MouseListener
  {
    public void mouseClicked(MouseEvent event)
    {

      if(event.getSource()==lb1)
      {
        if(j==1)
          x[1]=1;
        else
          x[1]=2;
        lb1.setIcon(icon);
      }
      public void mousePressed(MouseEvent event){}
      public void mouseEntered(MouseEvent event){}
      public void mouseReleased(MouseEvent event){}
      public void mouseExited(MouseEvent event){} // error here

      Horizon.this.checkWinner(); 

      if(i==9)
      {
        JOptionPane.showMessageDialog(null, "The game is a draw", "Draw", JOptionPane.OK_OPTION);
      }

    }
  }

}

删除方法调用后错误消失。

此错误的原因是什么,我该如何解决? 问候

【问题讨论】:

  • 你试过 checkWinner() 吗?
  • 正确缩进你的代码就可以解决你的问题。
  • 您发布的代码中有很多语法错误。方法中定义的方法,i,j,x,lb1 未声明。如果您只是删除行 Horizon.this.checkWinner(); ,您的代码是否编译?

标签: java methods inner-classes


【解决方案1】:

您已将方法声明放在方法声明中。只需将所有这些声明移出mouseClicked:

  private class HandlerClass implements MouseListener
  {
    public void mouseClicked(MouseEvent event)
    {
      if(event.getSource()==lb1)
      {
        if(j==1)
          x[1]=1;
        else
          x[1]=2;
        lb1.setIcon(icon);
      }

      Horizon.this.checkWinner(); 

      if(i==9)
      {
        JOptionPane.showMessageDialog(null, "The game is a draw", "Draw", JOptionPane.OK_OPTION);
      }
    }

    public void mousePressed(MouseEvent event){}
    public void mouseEntered(MouseEvent event){}
    public void mouseReleased(MouseEvent event){}
    public void mouseExited(MouseEvent event){} // error here
  }

顺便说一句,我希望您使用 IDE 来开发 Java 代码。如果是这样,请了解如何自动重新格式化代码并定期使用此功能。在 Eclipse 中它是 Ctrl-Shift-F。

【讨论】:

  • 实际上,当用户单击标签时,我每​​次(在封闭类内部制作)都会调用检查函数。因此,每当用户单击时,都会调用检查功能。 “置于顶层”是什么意思
  • 抱歉,在此处发布代码时将方法声明放入另一个方法是一个错误。顺便说一句,谢谢
  • 为了将来参考,发布确切的语法错误消息。当然,确切的实际代码是必须的。
  • 我知道,但 Eclipse 给了我;令牌错误。所以如果我问了一个关于这种非常通用的语法错误的问题,它可能会被关闭
猜你喜欢
  • 2019-03-16
  • 1970-01-01
  • 2012-04-21
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2016-07-04
  • 1970-01-01
相关资源
最近更新 更多