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 循环只是重复创建控件,向其中一个(按钮)注册监听器,将控件放置在新窗口中,然后显示窗口。在进行下一次迭代之前,循环不会等待按钮被按下。所以你最终有很多 window ......

您希望在显示阶段时阻止代码,直到输入有效文件。 Stage 定义了一个 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();
});

最后,除非文件有效,否则禁用 OK 按钮,您可以使窗口不装饰(没有最小化、最大化或关键的关闭按钮)。那么除非输入有效文件,否则不可能关闭窗口,并且您可以完全摆脱循环。请注意,如果用户无法找出有效文件(没有逃生路线),这可能会让用户感到烦恼:
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 - 依赖 org.apache.httpcomponents :httpclient:4. 5 被忽略以进行调试,因为它可能与提供的内部版本冲突

java - Primefaces selectOneMenu无法正确显示

java - intellij - 清理代码

java - 更改JDK版本的问题

java - 如何在Java中读取数字的每个数字

c++ - 在调试期间,我的程序跳至最近的while语句而不会中断或继续[C++]

java - 记录所有在我的对象上获得锁定的线程

java - Tomcat 7 Liferay 6.2关于损坏的数据库的奇怪错误

java - Java Servlet字符串到JQuery Ajax输出乱码

Java - 从不退出 While 循环