Build a Java Swing Arithmetic Quiz App: Random Questions, Instant Scoring, and GUI Design

This visual arithmetic quiz app is built with Java Swing. Its core capabilities include random addition question generation, four-option multiple-choice answers, instant scoring, and cumulative score display. It solves the weak interaction and poor user experience of console programs, making it a strong beginner project for learning GUI development. Keywords: Java Swing, arithmetic quiz, random question generation.

This project uses Java Swing to build a beginner-friendly graphical practice application.

[Technical Specification Snapshot]

Parameter Description
Programming Language Java
GUI Framework Swing
Runtime Model Desktop window application
Question Type Random addition within the range of 1-50
Interaction Model Local event-driven ActionListener
Total Questions 10
Number of Options 4
Star Count Not provided in the original article
Core Dependencies javax.swing, java.awt, java.util.Random

The core value of this project lies in combining basic arithmetic practice with event-driven UI programming.

The original program consists of three parts: UI construction, question generation, and answer evaluation. Compared with a command-line version, a Swing window creates a complete interaction loop across question display, button clicks, and score feedback. That makes it a better fit for classroom assignments and introductory Java GUI practice.

From an implementation perspective, the program extends JFrame as the main window and implements ActionListener to handle events from all four buttons in a unified way. This structure is clear and makes it easy to separate the two main flows: displaying questions and processing answers.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;

public class QuizApp extends JFrame implements ActionListener {
    int num1, num2, correctAnswer; // The two operands and the correct answer for the current question
    int current = 0, score = 0;
    final int total = 10; // Fixed number of questions

    JLabel questionLabel, infoLabel;
    JButton a, b, c, d;
    Random random = new Random();

    public QuizApp() {
        setTitle("中文算术答题小程序");
        setSize(500, 350);
        setLayout(null); // Use absolute positioning for quick component placement
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // Handle button click events in one place
    }
}

This skeleton defines the window, state fields, and event entry point. It forms the foundation of the entire quiz workflow.

The UI layer creates a directly usable quiz experience.

The program uses one question label, four option buttons, and one information label to form a minimal viable interface. The question area displays the expression, the buttons serve as the input mechanism, and the bottom label shows the current question number and score. The interaction path is short and straightforward.

The advantage of this layout is its low learning curve, but absolute positioning also has a clear drawback: poor scalability. When the window size changes or the font settings differ, component positions may become misaligned. In later iterations, BorderLayout or GridLayout would be a better choice.

questionLabel = new JLabel("", JLabel.CENTER);
questionLabel.setFont(new Font("微软雅黑", Font.PLAIN, 28)); // Set the question font to improve readability
questionLabel.setBounds(50, 50, 400, 50);
add(questionLabel);

a = new JButton("选项A");
b = new JButton("选项B");
c = new JButton("选项C");
d = new JButton("选项D");

// Set the position and size of the four buttons
 a.setBounds(80, 130, 150, 50);
 b.setBounds(260, 130, 150, 50);
 c.setBounds(80, 200, 150, 50);
 d.setBounds(260, 200, 150, 50);

This code places the components for the main quiz interface and represents the visible interaction layer of the application.

The question generation logic builds addition problems with random numbers and refreshes four candidate answers.

Each time the app moves to the next question, it generates two integers between 1 and 50 and calculates the correct answer. It then uses four buttons as candidate options, randomly chooses one button to hold the correct answer, and fills the others with random distractor values.

This strategy is easy to implement, but it has a practical flaw: distractors may be duplicated, and they may even match the correct answer. That can result in multiple buttons showing the same correct value. To improve question quality, the program should add deduplication logic and control the distance between distractors and the correct answer.

void nextQuestion() {
    num1 = random.nextInt(50) + 1; // Generate a random number from 1 to 50
    num2 = random.nextInt(50) + 1;
    correctAnswer = num1 + num2;   // Calculate the correct answer

    questionLabel.setText(num1 + " + " + num2 + " = ?");
    infoLabel.setText("第 " + (current + 1) + " 题 | 当前得分:" + score);

    JButton[] options = {a, b, c, d};
    for (JButton btn : options) {
        btn.setText(String.valueOf(random.nextInt(100) + 1)); // Fill with incorrect candidate values first
        btn.setEnabled(true);
    }

    options[random.nextInt(4)].setText(String.valueOf(correctAnswer)); // Place the correct answer randomly
}

This logic is responsible for generating questions, rendering the prompt, and refreshing the options. It is the core business flow of the program.

The answer evaluation logic delivers instant feedback and cumulative scoring through button events.

When the user clicks a button, the program reads the button text, converts it to an integer, and compares it with the correct answer. If the answer is correct, the score increases by one. Otherwise, a dialog shows the correct value. The program then proceeds to the next question. After all questions are completed, it displays the final score in a dialog box and exits.

This flow demonstrates Swing’s typical event-driven model: a user action triggers an event, the event handler updates application state, and the updated state drives UI changes in return. For beginners, this makes GUI interaction easier to understand than a console loop.

@Override
public void actionPerformed(ActionEvent e) {
    JButton clicked = (JButton) e.getSource(); // Get the clicked button
    int userAnswer = Integer.parseInt(clicked.getText()); // Read the answer selected by the user

    if (userAnswer == correctAnswer) {
        score++; // Increase the score when the answer is correct
        JOptionPane.showMessageDialog(this, "✅ 回答正确!太棒了!");
    } else {
        JOptionPane.showMessageDialog(this, "❌ 答错啦,正确答案是:" + correctAnswer);
    }

    current++; // Move to the next question
    nextQuestion();
}

This code implements the full loop from user click to result feedback.

The screenshots clearly show that the program supports complete question presentation and result feedback.

image AI Visual Insight: This screenshot shows the main quiz interface. A large-font addition problem appears in the center, four buttons are arranged in a two-by-two grid, and the bottom area displays the question number and score. This indicates that the application has completed window layout, question rendering, and basic status bar design.

微信图片_20260422170404_6161_2 AI Visual Insight: This screenshot captures the feedback flow after the user selects an answer. The app typically uses a dialog box to show whether the answer is correct, which confirms that event listeners are connected to the evaluation logic and that the UI is an executable interaction flow rather than a static display.

微信图片_20260422170404_6162_2 AI Visual Insight: This screenshot likely shows another randomly generated question with a different option layout. It reflects that the question data refreshes dynamically, which means the program can reset the prompt, update candidate answers, and keep the interface continuously usable after each round.

微信图片_20260422170453_6165_2 AI Visual Insight: This screenshot most likely corresponds to the final score or an end-of-session dialog. It suggests that the program includes question-count boundary control and a completion mechanism that summarizes the score and ends the session after the fixed number of questions.

This project works well as an introductory Java GUI example, but it still has clear room for engineering improvements.

First, add set-based deduplication for incorrect options to prevent repeated answers. Second, separate the program into classes such as a question generator, answer evaluator, and UI controller to reduce coupling. Third, add subtraction, multiplication, and difficulty levels so the program can evolve from a demo into an extensible practice tool.

For educational use cases, you could also add answer timing, incorrect-answer review, and score persistence. At that point, the project would no longer be just a Swing practice exercise. It would become a complete lightweight desktop learning application.

FAQ

1. Why is this program suitable for Java beginners?

Because it combines Swing UI development, random number generation, event handling, conditional logic, and state management in a single project. It connects multiple foundational concepts in one practical example.

2. What is the biggest technical flaw in the current implementation?

The biggest issue is that option generation does not deduplicate values. Distractors may repeat, and the correct answer may appear more than once. In a real project, you should use a collection to validate uniqueness among candidate values.

3. If I continue iterating on this project, what should I prioritize first?

Start by improving the layout manager and the question generator. The first improves UI adaptability, while the second improves question quality. Once both are addressed, the project’s maintainability and usability will improve significantly.

Core Summary: This article reconstructs a Java Swing arithmetic quiz app and focuses on random question generation, four-choice interaction, automatic scoring, and GUI layout implementation, while using screenshots to explain its interface structure, core code, and optimization opportunities.