JavaFx陷入while循环

时间:2016-10-08 03:51:53

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

我是JavaFx的新手,正在尝试编写我的刽子手游戏。我正处于需要检查以查看包含我的词典的文件是否存在的位置。如果没有要求用户输入其位置。我试图在一个弹出窗口中执行此操作,要求用户输入位置并点击一个按钮,此按钮将导致textbox.getText()被保存并加载。如果它是一个不好的位置,重复。我故意拼错了位置以使这个弹出窗口运行,但它被困在一个while循环中并迫使我结束应用程序。我将它作为一个新的场景运行,但我仍然坚持下一步做什么。这是我的Controller.java

仅供参考:虽然这是大学的家庭作业,但我没有注册。我在残疾,我的朋友正在上课。我正试图通过玩他的任务来保持忙碌。喜欢编码,这让我很忙,最新,我开始学习新东西。

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;
    }

}

1 个答案:

答案 0 :(得分:2)

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

您希望在显示舞台时阻止代码,直到输入有效文件。 Stage定义了一个showAndWait方法,该方法将显示窗口,然后阻止执行,直到窗口被解除。 (注意,这实际上是你应该在FX应用程序线程上调用的唯一阻塞方法。它确实可以确保UI在代码执行被阻止时保持响应。)所以一种方法是调用{在循环中{1}},因为这会阻止循环进入下一次迭代,直到窗口被解除:

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();
});

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

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();
});

最后一条评论:要允许用户选择文件,您可以考虑使用FileChoosertutorial)。