简体   繁体   English

调用内部类中的封闭类方法

[英]Calling Enclosing Class methods inside Inner Class

I am calling the enclosing class method inside inner class, but I get syntax error. 我在内部类中调用封闭类方法,但是出现语法错误。 Here is the code: 这是代码:

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

    }
  }

}

The error goes away when remove the method call. 删除方法调用时,错误消失。

What is the reason for this error and how can I solve it? 此错误的原因是什么,我该如何解决? Regards 问候

You have placed method declarations inside a method declaration. 您已将方法声明放置在方法声明中。 Just move all those declaration outside mouseClicked : 只需将所有这些声明移到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
  }

By the way, I hope you are using an IDE to develop Java code. 顺便说一句,我希望你使用的是IDE开发Java代码。 If so, find out how to automatically reformat the code and use this feature regurarly. 如果是这样,请找出如何自动重新格式化代码并定期使用此功能。 In Eclipse it ist Ctrl-Shift-F. 在Eclipse中,按Ctrl-Shift-F。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM