如何在Eventhandler中创建新窗格?

时间:2015-12-26 18:05:00

标签: javafx pane

我正在制作调查问卷并想要多个“页面”。每个页面都是一个窗格。我想创建一个“下一个按钮”,将用户导航到下一个窗格,其中另一个问题列表将等待他们回答。我在javafx的事件处理程序中写了什么?通过创建一个新窗格,我对pane1的回答是否安全?

1 个答案:

答案 0 :(得分:0)

我会举个例子。我已将以下内容声明为全局变量:questions, answers, currentQuestionQuestions是包含问题的字符串列表。 Answers是包含用户答案的​​字符串列表。 CurrentQuestion是当前问题的索引。

调用ButtonAction(点击)时,我会更新currentQuestion(添加1),因此会转到下一个问题。我已将Stage作为变量传递给我,因此当我点击按钮时我可以更新它。

它的作用是,它为Scene调用一个新的构造函数。然后,我在setScene上使用Stage来更新grahics。

另一种方法是使用State Machine。创建一个更改Pane的类。然后,Button Action将改变该类的状态(例如,它将具有整数状态,1,2,3(3个不同的问题)。

    public class JavaFXApplication4 extends Application {

    int curPage = 1;
    String [] questionnaire = new String[]{
            "Why is the sun blue?", "Why is iPhones better than Androids", "Why are moons bad for your skin",
            "Who am I?", "To be or not to be?", "Yes or no?", "Will you rain on my parade?", "Etc questions"
        };
    String [] answer;
    Scene s;

   public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        answer = new String[questionnaire.length];

        Pane curPane = differentPage(questionnaire[curPage-1], questionnaire.length, stage);

        s = new Scene(curPane);
        stage.setScene(s);
        stage.show();
    }

    public void setSceneAgain(Stage stage){
        Pane curPane = differentPage(questionnaire[curPage-1], questionnaire.length, stage);
        s = new Scene(curPane);
        stage.setScene(s);
       }

    public Pane differentPage(String question, int numQuestions, final Stage stage){
        Pane p = new Pane();

        VBox vbo = new VBox();

        Label l = new Label("Page: " + curPage);
        Label r = new Label(question);
        vbo.getChildren().addAll(l,r);

        // 10 = lastpage
        if(curPage < numQuestions){
            Button nextButton = new Button("Next");
            nextButton.setOnAction(new EventHandler<ActionEvent>() {
                    @Override 
                    public void handle(ActionEvent e) {
                        // set answer[curPage-1] here to whatever the person chose
                        curPage++;
                        setSceneAgain(stage);
                    }
                });
            vbo.getChildren().add(nextButton);
        } else {
            Button finishButton = new Button("Finish");
            finishButton.setOnAction(new EventHandler<ActionEvent>(){
                @Override
                public void handle(ActionEvent e){
                    //finish event
                }
            });
            vbo.getChildren().add(finishButton);
        }

         p.getChildren().add(vbo);
        return p;
    }

}