【问题标题】:While loop not executing with jframe implementation虽然循环不与 jframe 实现一起执行
【发布时间】:2016-05-24 16:33:51
【问题描述】:

所以基本上我有一个公共静态 void main 方法,它创建一个框架和一个级别,该级别是一个面板,然后添加到 jframe 但之后代码似乎没有检查我在 main 中的 while 循环我知道它不是因为只要框架可见就应该检查我的while循环,如果它到达这一点并且它没有,它应该在控制台窗口中打印一行。 任何帮助,将不胜感激!另外,是的,我知道打印行会弹出一个控制台窗口窗口,但实际上并没有把它放在框架中。我为此 while 语句创建了一个单独的函数,我只是将 println 用于调试目的。

public class Main extends JFrame 
{
  public static void main(String[]args)
  {
  System.out.println("LevelStart");
  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


  while (m2.isVisible())
   {
      System.out.println("If this displays something is wrong with my checkWin method"); 
      if(l.checkWin())
     {
       System.out.println("If this displays something is wrong with my checkWin method");

     }  
    }
   }
  }

【问题讨论】:

    标签: java swing while-loop


    【解决方案1】:

    您的 while 循环违反了 Swing 线程规则,应该被删除。

    无论如何,你的程序设计应该改进。您不应该创建新的 JFrame 对象,而应该创建一个使用 CardLayout 的 JPanel,将所有级别的 JPanel 添加到此 CardLayout-使用 JPanel,在添加级别时使用唯一的字符串常量。然后,您可以通过调用适当的 CardLayout 方法轻松交换级别,next(...)show(...)

    【讨论】:

    • 即使我这样做很容易适应所以我可能会这样做我仍然需要在我达到所有级别后检查我的主要胜利布局。唯一的区别是我将有一个框架,然后我不会处理每个框架来更改级别,而是显示下一个面板,所以我想以类似的方式检查我的获胜条件吗?
    • "I still would need to check for my win in the main after I had all the levels to the layout." -- 为什么?这是一个糟糕的设计。主要方法应该只是启动 GUI,然后移开。您的代码表明您还没有完全理解事件驱动的 GUI 编程。
    • @RichieZ:您将通过侦听可能导致它发生的事件来检查“获胜条件”。您要做的最后一件事是使用循环进行轮询,同样,您需要阅读事件驱动编程,因为您的轮询想法与您的使用方式背道而驰。
    【解决方案2】:

    您不需要 while 循环。 Swing 是事件驱动的,一旦您创建了 JFrame 并使其可见,该框架将保持打开状态,直到用户关闭该框架。

    另外,如果您需要子窗口,那么您应该使用 JDialog,而不是另一个 JFrame。

    阅读 How to Make Frames 上的 Swing 教程中的部分,了解一个简单的示例来帮助您入门。

    【讨论】:

    • 是的,我明白这一点。 while 循环的要点是检查另一个类的实例字段,然后处理该帧。例如,如果该方法(这是一个访问器方法)返回 true,它将关闭框架。系统 println 只是为了找出 while 循环是否甚至执行它没有执行...
    • The point of the while loop is to check the instance field of another class and then to dispose of that frame - 该逻辑不应该在 main() 方法中。当实例变量更改时,该逻辑应该在类中。然后当变量改变时你关闭窗口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多