JavaFX:如何在显示GUI之前请求用户输入

时间:2013-10-06 17:00:38

标签: java user-interface javafx-2

我在Netbeans 7.3.1中遇到了一些JavaFX问题。我正在尝试制作一款能够完成游戏的游戏。程序应该询问用户是否公平,以及初始化模具以滚动的其他信息(例如边数)。单击滚动按钮时,它将滚动模具。

我的问题是,由于JavaFX在启动GUI时忽略了主程序,我不确定在GUI加载之前向用户询问此信息的位置(或如何)。

public class DiceGame extends Application {

@Override
public void start(Stage primaryStage) {
    Button btn = new Button();
    btn.setText("Roll Die!");
    btn.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent event) {
            // 
            // code for rolling a die goes here.
        }
    });

    StackPane root = new StackPane();
    root.getChildren().add(btn);

    Scene scene = new Scene(root, 300, 250);

    primaryStage.setTitle("Dice Game");
    primaryStage.setScene(scene);
    primaryStage.show();
}

/**
 * The main() method is ignored in correctly deployed JavaFX application.
 * main() serves only as fallback in case the application can not be
 * launched through deployment artifacts, e.g., in IDEs with limited FX
 * support. NetBeans ignores main().
 *
 * @param args the command line arguments
 */


public static void main(String[] args) {

    //ask user for n value to initialize a die object before the javafx ui is launched.

    System.out.println("Is your die loaded or fair? *Input 1 for fair and 2 for loaded* ");

    Scanner fair_or_loaded = new Scanner(System.in); //Determines fair or loaded die.
    int input = fair_or_loaded.nextInt();

    if (input == 1) {
        System.out.println("Input an N value for a fair die: ");
        Scanner user_input = new Scanner(System.in); //Created a fair die.
        int n = user_input.nextInt();
        Die D1 = new Die(n); //User created die.

    } else { //Loaded die is created. Need Scanner for loadedSide and LoadFactor.
        System.out.println("Input an N value for a loaded die: ");
        Scanner loaded_n_input = new Scanner(System.in);
        int loaded_n = loaded_n_input.nextInt(); //loaded n value created

        System.out.println("Input a side to be loaded: ");
        Scanner user_side = new Scanner(System.in);
        int side_loaded = user_side.nextInt(); //loaded side created

        System.out.println("Input a load factor: ");
        Scanner user_load = new Scanner(System.in);
        int factor_load = user_load.nextInt(); //load factor created

        LoadedDie DL = new LoadedDie(loaded_n, side_loaded, factor_load); //Loaded die is created.
    }

     launch(args);  
  }
}

非常感谢!

1 个答案:

答案 0 :(得分:2)

如该代码中的注释所述,JavaFX应用程序在正确启动时,不像传统Java应用程序那样使用main()方法 - 它们创建默认应用程序类的实例并调用其start方法

因此,如果您希望在显示GUI之前执行此代码,则必须在start方法的开头调用它。最好将相应的代码放在一个单独的方法中,然后在开始构建UI之前调用该方法。