JavaFx 陷入 while 循环

标签 java intellij-idea while-loop javafx-8 scenebuilder

我是 JavaFx 新手,正在尝试编写我的刽子手游戏。我现在必须检查保存我的词典的文件是否在那里。如果没有,请用户输入其位置。我试图在弹出窗口中执行此操作,要求用户输入位置并点击按钮,该按钮反过来将导致 textbox.getText() 被保存并加载。如果位置错误,请重复。我故意拼写错误了让这个弹出窗口运行的位置,但它陷入了 while 循环并迫使我结束应用程序。我将其作为一个新场景运行,但我不知道下一步该做什么。这是我的 Controller.java

仅供引用:虽然这是大学的家庭作业,但我没有注册。我患有残疾,我的 friend 正在上课。我试图通过完成他的作业来保持忙碌。热爱编码,这让我忙碌、了解最新情况,并且我可以学习新东西。

package sample;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class Controller {

    public Label welcomeLabel, guessesLettersLabel, GuessesRemainingLabel, currentStateLAbel, endGameMessageLabel;
    public Button newGameButton, exitButton, enterTextButton;
    public TextField enterTextBox;
    public boolean ynAnswer;
    public String textAnswer;
    Stage window;
    File inputFile;


    public void newGame() throws FileNotFoundException {

        Scanner input = new Scanner(System.in);

        inputFile = new File("src\\sample\\HangmanLexcon.txt");
        while(!inputFile.exists()) {
            window = new Stage();
            window.initModality(Modality.APPLICATION_MODAL);
            window.setTitle("File was not found.");
            window.setMinWidth(250);
            window.setMaxHeight(100);

            //form
            TextField fileInput = new TextField();
            Button inputButton = new Button("Upload File");
            inputButton.setOnAction(e -> {
                inputFile = new File(fileInput.getText());
                window.close();
            });


            //Layout
            VBox layout = new VBox(10);
            layout.setPadding(new Insets(20, 20, 20, 20));
            layout.getChildren().addAll(fileInput, inputButton);

            //Set scene and show in window.
            Scene scene = new Scene(layout, 300, 100);
            window.setScene(scene);
            window.show();

        }

        Hangman newGame = new Hangman(inputFile.toString());
        welcomeLabel.setText("A word has been selected. Good luck, and may the odds ever be in your favor.");

        guessesLettersLabel.setText("Guessed Letters: " + newGame.getGuessedLetters());
        GuessesRemainingLabel.setText("Guesses remaining: " + newGame.getIncorrectGuessesRemaining());
        currentStateLAbel.setText("Current State: " + newGame.getCurrentState());

    }

    public void enterTextButton(){
        System.out.println("You pressed enter...");
    }

    public void enterText(){
        enterTextButton();
    }

    /**
     * If the player closed to exit the game or hit the X button this method will ask if they are
     * sure they wish to exit before quiting the game.
     */
    public void exitGame(){
        Boolean answer = desplayYesNoMessgae("Exit", "Are you sure you want to exit?");
        if(answer)
            System.exit(0);
    }

    public boolean desplayYesNoMessgae(String title, String message){
        Stage window = new  Stage();
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setMinWidth(250);
        Label label1 = new Label();
        label1.setText(message);

        //Create two buttons, yes and no
        Button yesButton = new Button("Yes");
        Button noButton = new Button("No");

        //If yes ic clucked, set answer to true.
        yesButton.setOnAction(e -> {
            ynAnswer = true;
            window.close();
        });

        //if no is clicked, set answer to false.
        noButton.setOnAction(e -> {
            ynAnswer =  false;
            window.close();
        });

        VBox layout = new VBox(10);
        layout.getChildren().addAll(label1, yesButton, noButton);
        layout.setAlignment(Pos.CENTER);
        Scene scene = new Scene(layout);
        window.setScene(scene);
        window.showAndWait();

        return ynAnswer;
    }

    public String desplayTextMessgae(String title, String message){
        Stage window = new  Stage();
        window.initModality(Modality.APPLICATION_MODAL);
        window.setTitle(title);
        window.setMinWidth(250);
        Label label1 = new Label();
        label1.setText(message);

        //form
        TextField nameInput = new TextField();
        Button loadBbutton = new Button("Upload");
        loadBbutton.setOnAction(e -> {
            textAnswer = nameInput.getText();
            window.close();
        });


        //Layout
        VBox layout = new VBox(10);
        layout.setPadding(new Insets(20, 20, 20, 20));
        layout.getChildren().addAll(nameInput, loadBbutton);

        //Set scene and show in window.
        Scene scene = new Scene(layout, 300, 100);
        window.setScene(scene);
        window.show();

        return textAnswer;
    }

}

最佳答案

在 GUI 编程中,在考虑基于循环的方法之前,请始终考虑事件驱动的方法。 while 循环只是重复创建控件,向其中一个控件(按钮)注册一个监听器,将控件放置在新窗口中,然后显示该窗口。循环不会等待按下按钮才继续下一次迭代。所以你最终会得到很多窗口......

您希望代码在显示阶段时阻塞,直到输入有效文件为止。阶段定义了 showAndWait方法将显示窗口,然后阻止执行,直到窗口关闭。 (请注意,这本质上是您应该在 FX 应用程序线程上调用的唯一阻塞方法。它具有一些魔力,可以确保 UI 在代码执行被阻塞时保持响应。)因此,一种方法是调用 showAndWait 在循环中,因为这将阻止循环进行到下一次迭代,直到窗口关闭:

while(!inputFile.exists()) {
    window = new Stage();
    window.initModality(Modality.APPLICATION_MODAL);
    window.setTitle("File was not found.");
    window.setMinWidth(250);
    window.setMaxHeight(100);

    //form
    TextField fileInput = new TextField();
    Button inputButton = new Button("Upload File");
    inputButton.setOnAction(e -> {
        inputFile = new File(fileInput.getText());
        window.close();
    });


    //Layout
    VBox layout = new VBox(10);
    layout.setPadding(new Insets(20, 20, 20, 20));
    layout.getChildren().addAll(fileInput, inputButton);

    //Set scene and show in window.
    Scene scene = new Scene(layout, 300, 100);
    window.setScene(scene);
    window.showAndWait();

}

如果文件存在,您可以通过仅关闭窗口来使此操作变得更好:

inputButton.setOnAction(e -> {
    inputFile = new File(fileInput.getText());
    if (inputFile.exists()) {
        window.close();
    }
});

除非文件存在,否则您可以通过禁用按钮来使其变得更好:

TextField fileInput = new TextField();
Button inputButton = new Button("Upload File");
inputButton.setDisable(true);
fileInput.textProperty().addListener((obs, oldText, newText) -> 
    inputButton.setDisable( ! new File(newText).exists() ) );
inputButton.setOnAction(e -> {
    inputFile = new File(fileInput.getText());
    window.close();
});

或者使用绑定(bind):

TextField fileInput = new TextField();
Button inputButton = new Button("Upload File");
inputButton.disableProperty().bind(Bindings.createBooleanBinding(
    () -> ! new File(fileInput.getText()).exists(), 
    fileInput.textProperty()));
inputButton.setOnAction(e -> {
    inputFile = new File(fileInput.getText());
    window.close();
});

最后,除非文件有效,否则禁用“确定”按钮,您可以使窗口未经修饰(没有最小化、最大化,或者最重要的是,关闭按钮)。那么除非输入了有效的文件,否则不可能关闭窗口,并且您可以完全摆脱循环。请注意,如果用户无法找出有效文件(没有逃生路线),这可能会让用户感到烦恼:

if (! inputFile.exists()) {
    window = new Stage();
    window.initModality(Modality.APPLICATION_MODAL);
    window.initStyle(StageStyle.UNDECORATED);
    window.setTitle("File was not found.");
    window.setMinWidth(250);
    window.setMaxHeight(100);

    //form
    TextField fileInput = new TextField();
    Button inputButton = new Button("Upload File");
    inputButton.disableProperty().bind(Bindings.createBooleanBinding(
        () -> ! new File(fileInput.getText()).exists(), 
        fileInput.textProperty()));
    inputButton.setOnAction(e -> {
        inputFile = new File(fileInput.getText());
        window.close();
    });


    //Layout
    VBox layout = new VBox(10);
    layout.setPadding(new Insets(20, 20, 20, 20));
    layout.getChildren().addAll(fileInput, inputButton);

    //Set scene and show in window.
    Scene scene = new Scene(layout, 300, 100);
    window.setScene(scene);
    window.showAndWait();
}

最后一条评论:为了允许用户选择文件,您可以考虑使用 FileChooser (tutorial)。

关于JavaFx 陷入 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39928495/

相关文章:

java - Android 上 SQLite 查询的语法错误

java - java中如何在一个文件中写入多次?

python - 需要帮助指定结束 while 条件

C 代码陷入无限的 do-while 循环

Java - 获取 StackOverflowError

Android调试器不断断开连接

android-studio - Android Studio 快速文档始终为 "fetching documentation"

预期的 JavaScript 表达式

r - 在 R 中使用带有 while 循环的 tryCatch

java - Java中按位运算符和位移位的有趣行为返回值