使用eventHandler的java gui中的IF Else语句

时间:2018-06-03 12:24:57

标签: java arrays javafx

我正在尝试复制我在GUI中的控制台中执行的代码。

if (age <18 && feelings.toUpperCase().equals("SAD")){
    System.out.println(phrase.sadQuotesBefore18[rand.nextInt(2)]);
} else if (age >= 18 && feelings.toUpperCase().equals("SAD") ) {
    System.out.println(phrase.sadQuotesAfter18[rand.nextInt(3)]);
} else if (age <18 && feelings.toUpperCase().equals("ANGRY")){
    System.out.println(phrase.angryQuotesBefore18[rand.nextInt(2)]);
} else if (age >= 18 && feelings.toUpperCase().equals("ANGRY")){
    System.out.println(phrase.angryQuotesAfter18[rand.nextInt(8)]);
} else if (age < 18  && feelings.toUpperCase().equals("HAPPY")){
    System.out.println(phrase.happyQuotesBefore18[rand.nextInt(2)]);
} else if (age >= 18 && feelings.toUpperCase().equals("HAPPY")){
    System.out.println(phrase.happyQuotesAfter18[rand.nextInt(4)]);
} else {
    System.out.println("You have entered and unknown combination, please try again");
}    

如下图所示。我在下面的代码中意识到我无法获得上面显示的else if和else语句。只有如下所示的if语句才有效。我是新手,所以任何帮助将不胜感激。

submitButton.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        if (agebox.getText().equals("<=18") && feelings.equals("Sad")) {

        }
        showAlert(AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Your Quote!", phrase.sadQuotesBefore18[rand.nextInt(3)]);
    }
}

1 个答案:

答案 0 :(得分:0)

不确定你的问题是什么,但至少你可以对if语句进行分类:

submitButton.setOnAction(new EventHandler<ActionEvent>() {
    @Override
    public void handle(ActionEvent event) {
        String quoteStr="";
        if (agebox.getText().equals("<18")) {
            if (feelings.equals("SAD")) {
               quoteStr = phrase.sadQuotesBefore18[rand.nextInt(3)];
            } else if (feelings.equals("ANGRY")) {
               quoteStr = phrase.angryQuotesBefore18[rand.nextInt(2)];
            } else if (feelings.equals("HAPPY")) {
               quoteStr = phrase.angryQuotesBefore18[rand.nextInt(2)];
            }
        }
        else if (agebox.getText().equals(">=18")) {
            if (feelings.equals("SAD")) {
               quoteStr = phrase.sadQuotesAfter18[rand.nextInt(3)];
            } else if (feelings.equals("ANGRY")) {
               quoteStr = phrase.angryQuotesAfter18[rand.nextInt(8)];
            } else if (feelings.equals("HAPPY")) {
               quoteStr = phrase.angryQuotesAfter18[rand.nextInt(4)];
            }
        }

        showAlert(AlertType.CONFIRMATION, gridPane.getScene().getWindow(), "Your Quote!", quoteStr);
    }
}