Java Typing Speed Test – Enhance Your Speed and Accuracy

In this project, we will create a Typing speed test using the Java language and the JSwing for the GUI. The application will provide users with a passage of text to type, calculate their typing accuracy and speed, and display the results in real-time.

About Java Typing Speed Test

This project aims to guide you through the process of creating a Java Swing application for measuring typing speed and accuracy. By the end of the project, you will have a working application that demonstrates event handling, user interface design, and string manipulation in Java.

Prerequisites for Typing Speed Test Using Java

  • Basic knowledge of Java programming concepts, including classes, objects, methods, and event handling.
  • Familiarity with Java Swing library and graphical user interface (GUI) development.
  • Experience using an integrated development environment (IDE) such as Eclipse or IntelliJ IDEA to write and run Java code.

Download Java Typing Speed Test Project

Please download the source code of Java Typing Speed Test Project from the following link: Java Typing Speed Test Project Code.

Steps to Create Java Typing Speed Test using Java

Here is the complete code for the Typing Speed test:

package school.Firstcode;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.Random;

@SuppressWarnings("serial")
public class TypingSpeedTest extends JFrame {
    private JTextArea passageTextArea;
    private JTextArea inputTextArea;
    private JButton startButton;
    private JLabel accuracyLabel;
    private JLabel speedLabel;

    private String passage;
    private int typedWords;
    private int correctWords;
    private long startTime;

    public TypingSpeedTest() {
        setTitle("Typing Speed Test by Firstcode");
       
        setSize(538, 609);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel();
        panel.setLayout(null);

        passageTextArea = new JTextArea();
        passageTextArea.setEditable(false);
        passageTextArea.setLineWrap(true);
        passageTextArea.setWrapStyleWord(true);
        passageTextArea.setFont(new Font("Arial", Font.PLAIN, 14));
        JScrollPane scrollPane = new JScrollPane(passageTextArea);
        scrollPane.setBounds(0, 27, 530, 240);
        panel.add(scrollPane);

        inputTextArea = new JTextArea();
        inputTextArea.setBounds(0, 280, 530, 200);
        inputTextArea.setFont(new Font("Arial", Font.PLAIN, 14));
        inputTextArea.setLineWrap(true);
        inputTextArea.setWrapStyleWord(true);
        inputTextArea.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                updateTypingStats();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                updateTypingStats();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                updateTypingStats();
            }
        });
        panel.add(inputTextArea);

        startButton = new JButton("Start");
        startButton.setBounds(0, 0, 530, 27);
        startButton.setFont(new Font("Arial", Font.PLAIN, 14));
        startButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (startButton.getText().equals("Start")) {
                    startTest();
                } else {
                    resetTest();
                }
            }
        });
        panel.add(startButton);

        JPanel statsPanel = new JPanel(new GridLayout(2, 2));
        statsPanel.setBounds(0, 470, 530, 100);
        accuracyLabel = new JLabel("Accuracy:  ");
        accuracyLabel.setFont(new Font("Arial", Font.PLAIN, 14));
        statsPanel.add(accuracyLabel);

        speedLabel = new JLabel("Speed:  ");
        speedLabel.setFont(new Font("Arial", Font.PLAIN, 14));
        statsPanel.add(speedLabel);

        panel.add(statsPanel);

        getContentPane().add(panel);

        resetTest();

        setVisible(true);
    }

    public static String getRandomPassage() {
        String[] passages = {
                "India shares its borders with Pakistan, China, Nepal, Bhutan, Bangladesh, and Myanmar.",

                "With a rich cultural heritage, India is known for its diverse traditions, languages, and religions.\n" +
               
                "India is also renowned for its classical music, dance forms like Bharatanatyam and Kathak, and traditional festivals such as Diwali and Holi.",

           +
                "The country is also known for its information technology industry and has emerged as a global hub for software services and outsourcing.",

                "In terms of natural beauty, India offers diverse landscapes ranging from the snow capped Himalayas in the north to the pristine beaches of Goa and Kerala in the south.\n" +


+
                "India is also blessed with iconic rivers like the Ganges and the majestic Thar Desert in Rajasthan."
        };


        Random random = new Random();
        int index = random.nextInt(passages.length);
        return passages[index];
    }

    
    private void resetTest() {
        passage = getRandomPassage();
        typedWords = 0;
        correctWords = 0;

        passageTextArea.setText(passage);
        inputTextArea.setText("");
        accuracyLabel.setText("Accuracy:  ");
        speedLabel.setText("Speed:  ");
        startButton.setText("Start");
        inputTextArea.setEditable(false);
    }

    private void startTest() {
        typedWords = 0;
        correctWords = 0;
        startTime = System.currentTimeMillis();

        inputTextArea.setText("");
        accuracyLabel.setText("Accuracy:  ");
        speedLabel.setText("Speed:  ");
        inputTextArea.setEditable(true);
        inputTextArea.requestFocus();

        startButton.setText("Reset");
    }

    private void updateTypingStats() {
        String inputText = inputTextArea.getText();

        String[] inputWords = inputText.split("\\s+");
        String[] passageWords = passage.split("\\s+");

        typedWords = inputWords.length;
        correctWords = 0;

        for (int i = 0; i < Math.min(passageWords.length, typedWords); i++) {
            if (inputWords[i].equals(passageWords[i])) {
                correctWords++;
            }
        }

        int accuracy = (int) (((double) correctWords / typedWords) * 100);

        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        long elapsedTime = System.currentTimeMillis()   startTime;
        double minutes = elapsedTime / 60000.0; // Converting milliseconds to minutes
        double speed = typedWords / minutes; // Speed in words per minute
        String formattedSpeed = decimalFormat.format(speed);

        accuracyLabel.setText("Accuracy: " + accuracy + "%");
        speedLabel.setText("Speed: " + formattedSpeed + " wpm");
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TypingSpeedTest::new);
    }
}

Step by step implementation of the Typing Speed Test code:

1. Import the necessary Java Swing packages:

  • javax.swing.*
  • javax.swing.event.DocumentEvent
  • javax.swing.event.DocumentListener
  • java.awt.*
  • java.awt.event.ActionEvent
  • java.awt.event.ActionListener
  • java.text.DecimalFormat
  • java.util.Random

2. Define the “TypingSpeedTest” class, which extends “JFrame” to create the main GUI window for the typing speed test.

3. Create instance variables for the GUI components:

  • “passageTextArea”: A “JTextArea” to display the passage for typing.
  • “inputTextArea”: A “JTextArea” to input the user’s typed text.
  • “startButton”: A “JButton” to start or reset the typing test.
  • “accuracyLabel”: A “JLabel” to display the typing accuracy.
  • “speedLabel”: A “JLabel” to display the typing speed.

4. Define additional variables:

  • “passage”: A “String” to store the randomly selected passage for typing.
  • “typedWords”: An “int” to keep track of the number of words typed by the user.
  • “correctWords”: An “int” to keep track of the number of correctly typed words.
  • “startTime”: A “long” to store the starting time of the typing test.

5. Implement the constructor “TypingSpeedTest()”:

  • Set the frame’s title, size, default close operation, and location.
  • Create a panel and set its layout to null.
  • Create and configure the passageTextArea using “JTextArea”.
  • Create and configure the inputTextArea using “JTextArea”.
  • Add a “DocumentListener” to the inputTextArea to update typing statistics.
  • Create and configure the startButton using “JButton”.
  • Add an “ActionListener” to the startButton to handle the start and reset actions.
  • Create a statsPanel using “JPanel” and set its layout to a 2×2 grid.
  • Create and configure the accuracyLabel using “JLabel”.
  • Create and configure the speedLabel using “JLabel”.
  • Add the accuracyLabel and speedLabel to the statsPanel.
  • Add the statsPanel to the main panel.
  • Add the main panel to the frame’s content pane.
  • Call the “resetTest()” method to initialize the test.
  • Set the frame visible.

6. Implement the “getRandomPassage()” method:

  • Define an array of passages containing different strings.
  • Use the “Random” class and generate an index and select one passage from the array.
  • Return the selected passage.

7. Implement the “resetTest()” method:

  • Call the “getRandomPassage()” method to get a random passage.
  • Reset the “typedWords” and “correctWords” variables to 0.
  • Set the passageTextArea to display the selected passage.
  • Clear the inputTextArea.
  • Set the accuracyLabel and speedLabel to their initial values.
  • Set the startButton text to “Start”.
  • Disable the inputTextArea.

8. Implement the “startTest()” method:

  • Reset the “typedWords” and “correctWords” variables to 0.
  • Set the “startTime” to the current system time.
  • Clear the inputTextArea.
  • Set the accuracyLabel and speedLabel to their initial values.
  • Enable the inputTextArea for typing.
  • Set the focus on the inputTextArea.
  • Set the startButton text to “Reset”.

9. Implement the “updateTypingStats()” method:

  • Get the text from the inputTextArea.
  • Split the input text and the passage into arrays of words.
  • Update the “typedWords” with the length of the inputWords array.
    Reset the “correctWords” to 0.
  • Iterate over the words up to the minimum length of inputWords and passageWords.
  • If the word at the current index matches, increment “correctWords”.
  • Calculate the accuracy as the percentage of “correctWords” out of “typedWords”.
  • Format the elapsed time in minutes.
  • Calculate the speed as “typedWords” divided by minutes.
  • Update the accuracyLabel and speedLabel with the calculated values.

10. Implement the “main()” method:

Use “SwingUtilities.invokeLater()” to create an instance of “TypingSpeedTest” in the Event Dispatch Thread.

Java Typing Speed Test Ouput

java typing speed test output

Summary:

In this project, we developed a Typing Speed Test application using Java Swing. The application provides a user-friendly interface where users can practice typing and receive real-time feedback on accuracy and typing speed. Here are the main steps covered in this tutorial:

Setting up the GUI:

  • Creating a JFrame and setting its properties.
  • Adding text areas for displaying the passage and user input.
  • Adding a start button for initiating the typing test.
  • Including labels for accuracy and typing speed.
  • Generating a random passage:
  • Defining a set of passages.

Implementing event listeners:

  • Adding a DocumentListener to the input text area to track changes.
  • Handling document insert, remove, and change events to update typing statistics.
  • Handling test initialization and reset:
  • Initializing test variables and starting time when the start button is pressed.
  • Resetting variables and user interface components when the test is reset.

Updating typing statistics:

  • Calculating the number of typed words and correct words.
  • Calculating accuracy as a percentage of correct words.
  • Calculating typing speed in words per minute based on elapsed time.

You can further enhance the application by adding features such as user profiles, timed tests, or different difficulty levels.

Leave a Reply

Your email address will not be published. Required fields are marked *