首页 > 解决方案 > JavaFX - 创建为用户提示窗口暂停的逻辑循环

问题描述

作为我熟悉 MVC 模型的努力的一部分,我正在尝试编写一个程序,该程序循环通过一组代码计算,同时偶尔暂停以提示用户输入在 JavaFX 中创建的自定义窗口,使用该输入继续计算直到达到某个结果以打破循环。这个想法是,对于每个窗口,用户选择一个选项,窗口关闭,然后逻辑继续,直到需要下一个用户输入。然后下一个窗口打开并继续该过程。根据用户输入的内容,下一个窗口中包含的选项可以更改。对于我的开始示例,窗口有四个按钮,数字为 1-4,并提示用户选择一个数字。我将我的代码归结为一些非常基本的东西:

public class LogicLoop()
{

public static AtomicInteger CHOICE; //Global variable to act as the user's current choice, as there is only ever one choice made at a time
public static boolean loopDone = false;

public static void main(String [] args)
{
    new Start().startLoop(); //Calls the class that extends Application to call the launch() command. Since launch() can only be called once, it needs to be outside the loop 
    logicLoop();
}

public void logicLoop()
{
    while(!loopDone)
    {
        Chooser chooser = new Chooser();
        chooser.show();
        int choice = CHOICE.get();
        CHOICE = null;
        doSomething(choice);
    }

    public doSomething(int choice)
    {
        //Set some other variables to modify how the next window will look
        //Potentially set loopDone to true;
    }

}

}

然后是我的选择器类:

public class Chooser()
{
    public int show()
    {
        Stage newStage = new Stage();
        createWindow(newStage); //method that sets up window based on global variables and calls show() on newStage. Each button in the window will close the stage. The CHOICE value will also be set based on the user's input
    }
}

createWindow() 创建的窗口具有带有以下 handle() 方法的按钮:

public void handle(ActionEvent event) {
            CHOICE = new AtomicInteger(btn.getValue()); //I made my own Button class that has a value variable and a getter() for it
            Stage stage = (Stage) btn.getScene().getWindow();
            stage.close();
}

我面临的问题是,当我的代码执行时,逻辑不会等待用户输入,然后继续通过 show() 方法。所以发生的事情是代码开始循环,并立即打开第一个窗口。同时,抛出 NullPointerException 是因为我的逻辑已经在尝试调用 CHOICE.get() 在用户甚至有时间输入任何值之前。因此,在选择一个按钮并关闭第一个窗口后,没有其他任何事情发生。

到目前为止,我已经尝试在我的 createWindow() 方法中使用 showAndWait() 方法,但它似乎没有任何区别。我尝试在选择器.show() 之后调用 wait() 命令,但它只是增加了延迟,然后我看到了相同的结果。根据我在 Stack Overflow 上找到的信息,我看到了很多使用 Platform.runLater() 方法的建议,但我看不出它在这里如何有效。如果 GUI 稍后运行,没有它,逻辑仍然会继续前进。我需要暂停逻辑循环直到窗口关闭,这似乎是 showAndWait() 的设计目的。最让我困惑的是我在研究一个答案时遇到的一个声明,它说实现一个基本的 MVC 框架不需要多线程,并且不建议初学者使用它。在这个阶段,我不确定这怎么可能。

我在这里想念什么?

标签: javauser-interfacejavafxmodel-view-controllerwindow

解决方案


推荐阅读