You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX按钮事件开发:实现问答切换功能的技术问询

Hey there! Let's upgrade your JavaFX quiz app to cycle through a list of questions automatically after each answer. Here's a straightforward, maintainable way to implement this:

First, let's define a simple Question class to encapsulate your question text. This makes it easy to extend later (like adding correct answers or custom feedback):

public class Question {
    private String text;

    public Question(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

Step 2: Set Up Your Question List & Tracking Variable

In your main Application subclass, initialize a list of questions and an index to track which question we're on:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;

public class QuizApp extends Application {
    private List<Question> questions;
    private int currentQuestionIndex = 0;
    private Label questionLabel;
    private Label feedbackLabel;

    @Override
    public void start(Stage primaryStage) {
        // Initialize your question list
        questions = new ArrayList<>();
        questions.add(new Question("Is JavaFX a GUI framework?"));
        questions.add(new Question("Is Java a compiled language?"));
        questions.add(new Question("Does Java support multiple inheritance?"));

        // UI Elements
        questionLabel = new Label();
        feedbackLabel = new Label();
        Button yesBtn = new Button("Yes");
        Button noBtn = new Button("No");

        // Load the first question when the app starts
        loadCurrentQuestion();

        // Button click handlers
        yesBtn.setOnAction(e -> handleAnswer("Yes, you are correct"));
        noBtn.setOnAction(e -> handleAnswer("No, that's not right"));

        // Layout setup
        VBox layout = new VBox(10, questionLabel, feedbackLabel, yesBtn, noBtn);
        layout.setStyle("-fx-padding: 20;");
        Scene scene = new Scene(layout, 300, 200);

        primaryStage.setTitle("Simple Quiz");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

Step 3: Add Helper Methods to Load Questions & Handle Answers

Add these two methods inside your QuizApp class to manage question switching and feedback:

private void loadCurrentQuestion() {
        if (currentQuestionIndex < questions.size()) {
            questionLabel.setText(questions.get(currentQuestionIndex).getText());
            feedbackLabel.setText(""); // Clear previous feedback
        } else {
            // All questions answered - show completion message
            questionLabel.setText("Quiz completed!");
            feedbackLabel.setText("Great job!");
            // Optional: Disable buttons here to prevent further clicks
        }
    }

    private void handleAnswer(String feedback) {
        feedbackLabel.setText(feedback);
        // Add a short delay before switching questions (better UX than instant change)
        javafx.application.Platform.runLater(() -> {
            currentQuestionIndex++;
            loadCurrentQuestion();
        });
        // Remove the runLater block if you want instant question switching
    }

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

Extra Tips for Improvement

  • Custom Feedback per Question: Extend the Question class to include yes/no feedback strings, so each question can have tailored responses instead of generic ones.
  • Reset Functionality: Add a "Reset Quiz" button to set currentQuestionIndex back to 0 and reload the first question.
  • Answer Tracking: If you want to score the quiz, add a boolean isCorrectYesAnswer field to the Question class and validate answers before showing feedback.
  • Styling: Use CSS to highlight feedback text in green/red based on correctness, or make buttons stand out more.

That's it! This implementation keeps your code clean, scalable, and easy to modify as you add more features to your quiz app.

内容的提问来源于stack exchange,提问作者Vlad Paskevits

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:45:52