【问题标题】:Action Listeners and inner classes java动作监听器和内部类 java
【发布时间】:2016-05-16 16:44:26
【问题描述】:

所以我的公共静态 void main 中有一个嵌套类。它似乎可以编译并且是正确的,但它应该执行的功能似乎没有执行。方法如下。

public static void main(String[]args)
{

  LevelOne l = new LevelOne();
  //Level Two not made yet just a place holder to show constructor with a different type
  LevelTwo l2 = new LevelTwo();
  //I make l2 first because the front frame is the last one created
  Main m = new Main(l2);
  Main m2 = new Main(l);
  //To switch levels i am going to load them all in advance and then when the beat the level it will close the frame

  class ChoiceListener implements ActionListener
  {
      Timer tm = new Timer(5, this);
      //timer is used for the actionlistener
      public void actionPerformed(ActionEvent e) 
   {
    if(l.checkWin())
   {
     m2.setVisible(false);
     m2.dispose();
    }
   }

    }

  }

这是它应该在其他类中访问表单级别 l 的变量。

public void setWin()
{
   this.checkWin = true;  
}

public boolean checkWin()
{
  return this.checkWin;  
} 

checkWin 是另一个类的私有实例字段。由于某种原因,当 checkWin 设置为 true 时,它​​仍然不会执行。任何帮助将不胜感激!

【问题讨论】:

  • Main 也是类的名称,这就是为什么构造函数会说 main 对不起,如果因此有任何混淆。
  • 您在哪里创建侦听器类的实例并使用它?你现在才宣布它。
  • 这些是 Java Swing/AWT 控件吗?因为如果他们是,我想我已经知道发生了什么:)

标签: java


【解决方案1】:

在main方法中添加下面一行

Timer tm = new Timer(5, new ChoiceListener());
tm.start();

并删除

Timer tm = new Timer(5, this);

来自ChoiceListener。还要将ChoiceListener移出类中的main方法,以便可以使用类实例进行实例化,或者将其设为静态,以便直接实例化。

【讨论】:

  • 我做到了,但它似乎仍然不起作用。我的意思是它编译但它似乎仍然没有执行。这可能与我的其他课程有关,但也可能与其他想法有关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多