Java Quiz Application – Compete, and Dominate Java’s Mysteries!

FREE Online Courses: Enroll Now, Thank us Later!

In today’s digital age, quizzes have become an engaging way to educate, entertain, and challenge individuals. With the rise of e-learning, quiz applications have become increasingly popular as a means of assessing knowledge, testing skills, and providing feedback. In this project, we will be exploring the creation of a quiz application using Java Swing and SQLite.

About Java Quiz Application

The main objective of this project is to provide step-by-step guidance on how to create a quiz application with a user-friendly interface using Java Swing and SQLite database. The project will cover the following aspects:

  • Creating a GUI for the quiz application using Java Swing.
  • Creating a SQLite database to store quiz questions and answers.
  • Creating an admin panel that allows the admin to add new questions, delete any question or user in the database, and view a list of all questions.
  • Creating a quiz panel where users can attempt the quiz and receive feedback on their performance.
  • Implementing functionalities such as quiz timer and score tracking.

By the end of this project, you will have the skills and knowledge necessary to develop a fully functional quiz application.

Prerequisite for Quiz Application using Java

Basic Java knowledge:
Eclipse IDE:
Java Swing library: Familiarity with the Java Swing library is also necessary, as it’s used to create the graphical user interface (GUI) of the quiz application.
SQLite JDBC driver: You’ll need to download and add the SQLite JDBC driver to your project. This driver is used to connect the quiz application to the SQLite database management system.
SQL basics: Finally, it’s important to have a basic understanding of SQL, the language used to manage and manipulate the SQLite database. This knowledge will be useful when creating and managing the quiz questions and answers in the database.

Download Java Quiz Application Project

Please download the source code of Java Quiz Application Project: Java Quiz Application Project Code

Steps to Create Quiz Application Project using Java

Following are the steps for developing the Java Quiz Application Project:

Step 1: Create a New Project in Eclipse

Step 2: Creating the required classes

This is the project structure and the required classes

AdminLogin.java

This class provides us with the admin login window

AdminPanel.java

This class will provide the admin panel functionality of deleting users and questions, viewing all the questions and adding new questions.

DataBase.java

This class contains the methods related to the database operations, such as adding the question or retrieving the questions etc.

ProfileChooser.java

This class provides us with the option of choosing which profile we want to log in. Also this will be our entry point for the application.

Question.java

We will use this class’s object to store the questions while retrieving them from the database.

Quiz.java

This class will provide us with the quiz window and its gui along with the timer and the next questions logic.

Register.java

This class will register new users and add them to the database.

UserLogin.java

Same as the AdminLogin but for the Users.

Below is the code for the classes

AdminLogin.java:

package org.projectgurukul;

import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;

public class AdminLogin  {

    private JFrame frame;
    private JTextField adminNameField;
    private JPasswordField passwordField;
    private final String  adminName = "Admin";
    private final String password = "1234";

    public AdminLogin() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setTitle("Admin Login");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        
        JLabel lblAdmin = new JLabel("Admin Name");
        lblAdmin.setBounds(0, 67, 173, 36);
        frame.getContentPane().add(lblAdmin);
        
        adminNameField = new JTextField();
        adminNameField.setBounds(222, 68, 184, 36);
        frame.getContentPane().add(adminNameField);
        adminNameField.setColumns(10);
        
        JLabel lblPassword = new JLabel("Password");
        lblPassword.setBounds(0, 134, 173, 36);
        frame.getContentPane().add(lblPassword);
        
        passwordField = new JPasswordField();
        passwordField.setBounds(220, 135, 184, 36);
        frame.getContentPane().add(passwordField);
        
        JButton btnLogin = new JButton("Login");
        btnLogin.setBounds(161, 201, 117, 25);
        btnLogin.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                if(adminNameField.getText().equals(adminName) && password.equals(new String(passwordField.getPassword()))) {					frame.dispose();
                    AdminPanel ap = new  AdminPanel(); 
                    
                }else {
                    JOptionPane.showMessageDialog(btnLogin, "Incorrect Username or Password");;
                }
                
            }
        });
        frame.getContentPane().add(btnLogin);
        frame.setVisible(true);
    }
}

AdminPanel.java:

package org.projectgurukul;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JComboBox;

public class AdminPanel extends JFrame {
    private JTextField option1Field;
    private JTextField option2Field;
    private JTextField option3Field;
    private JTextField option4Field;
    private JTextField answerField;
    private JTextField remIDfield;
    
    public AdminPanel() {
        setTitle("Admin Panel");
        setSize(635, 500);
        getContentPane().setLayout(new BorderLayout(0, 0));
        
        JPanel deletePanel = new JPanel();
        deletePanel.setBackground(new Color(53, 132, 228));
        getContentPane().add(deletePanel, BorderLayout.NORTH);
        deletePanel.setLayout(new GridLayout(0, 2, 0, 0));
        
        JComboBox<String> comboBox = new JComboBox<String>();
        comboBox.addItem("users");
        comboBox.addItem("question");
        deletePanel.add(comboBox);
        
        remIDfield = new JTextField();
        deletePanel.add(remIDfield);
        remIDfield.setColumns(10);
        
        JPanel inputPanel = new JPanel();
        inputPanel.setBackground(new Color(53, 132, 228));
        getContentPane().add(inputPanel, BorderLayout.CENTER);
        inputPanel.setLayout(new GridLayout(0, 2, 0, 10));
        
        JLabel lblQuestion = new JLabel("Question:");
        inputPanel.add(lblQuestion);
        
        JTextArea queTextArea = new JTextArea();
        inputPanel.add(queTextArea);
        
        JLabel lblOption = new JLabel("Option 1:");
        inputPanel.add(lblOption);
        
        option1Field = new JTextField();
        inputPanel.add(option1Field);
        option1Field.setColumns(10);
        
        JLabel lblOption2 = new JLabel("Option 2:");
        inputPanel.add(lblOption2);
        
        option2Field = new JTextField();
        option2Field.setColumns(10);
        inputPanel.add(option2Field);
        
        JLabel lblOption3 = new JLabel("Option 3:");
        inputPanel.add(lblOption3);
        
        option3Field = new JTextField();
        option3Field.setColumns(10);
        inputPanel.add(option3Field);
        
        JLabel lblOption4 = new JLabel("Option 4:");
        inputPanel.add(lblOption4);
        
        option4Field = new JTextField();
        option4Field.setColumns(10);
        inputPanel.add(option4Field);
        
        JLabel lblAnswer = new JLabel("Answer:");
        inputPanel.add(lblAnswer);
        
        answerField = new JTextField();
        answerField.setColumns(10);
        inputPanel.add(answerField);
        
        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setBackground(new Color(53, 132, 228));
        getContentPane().add(buttonsPanel, BorderLayout.EAST);
        buttonsPanel.setLayout(new GridLayout(0, 1, 0, 10));
        
        JButton btnAddQue = new JButton("Add Question");
        btnAddQue.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    String[] options =  {option1Field.getText(),option2Field.getText(),option3Field.getText(),option4Field.getText()};
                    DataBase.addQuestion(queTextArea.getText(),options, answerField.getText());
                    JOptionPane.showMessageDialog(btnAddQue,"Question Added Sucessfully", "Success", JOptionPane.INFORMATION_MESSAGE);
                } catch (SQLException e1) {
                    JOptionPane.showMessageDialog(btnAddQue,"Can't add Question\n"+e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    e1.printStackTrace();
                }
            }
        });
        buttonsPanel.add(btnAddQue);
        
        JButton btnRemove = new JButton("Remove ");
        btnRemove.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    
                    DataBase.delete(remIDfield.getText(), (String)comboBox.getSelectedItem());
                    JOptionPane.showMessageDialog(btnAddQue,"Deleted Sucessfully", "Success", JOptionPane.INFORMATION_MESSAGE);
                } catch (SQLException e1) {
                    JOptionPane.showMessageDialog(btnAddQue,"Delete Question\n"+e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    e1.printStackTrace();
                }
            }
        });
        buttonsPanel.add(btnRemove);
        
        JButton btnViewAllQuestions = new JButton("View All Questions");
        btnViewAllQuestions.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                showAllQuestions();
            }
        });
        buttonsPanel.add(btnViewAllQuestions);
        
        JButton btnExit = new JButton("Exit");
        btnExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        buttonsPanel.add(btnExit);
        
        JButton btnLogout = new JButton("Logout");
        btnLogout.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
                AdminLogin adminLogin = new AdminLogin();
            }
        });
        buttonsPanel.add(btnLogout);
        setVisible(true);
        
        
    }

    protected void showAllQuestions() {
        JFrame frame =  new JFrame();
        frame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        
        try {
            ArrayList<Question> questions = DataBase.getQuestionAns();
            JTextArea qTextArea = new JTextArea();
            qTextArea.setLineWrap(true);
            qTextArea.setWrapStyleWord(true);
            qTextArea.setEditable(false);
            JScrollPane scroll = new JScrollPane (qTextArea, 
                       JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

                    frame.add(scroll);
            for (Iterator iterator = questions.iterator(); iterator.hasNext();) {
                Question question = (Question) iterator.next();
                qTextArea.append("\nQ."+question.getQuestion()+"\n"+
                                "1."+question.getOp1()+"\n"+
                                "2."+question.getOp2()+"\n"+
                                "3."+question.getOp3()+"\n"+
                                "4."+question.getOp4()+"\n"+
                                "Ans."+question.getAns()+"\n"+
                                "---------------------------------------------"
                        );
                
            }
            frame.setSize(300, 300);
            frame.setTitle("Question List");
            frame.setVisible(true);			
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        
    }
    
}

DataBase.java

  • dbInit() method: This method initializes the database by creating two tables if they don’t exist in the database. The tables are users and questions. The user table stores user information, while the question table stores questions, options, and answers for a quiz. This method uses an SQLiteDataSource to connect with the database.
  • addUser() method: This method adds a new user to the users’ table of the database. It takes four parameters: userID, username, email, and password. It creates a prepared statement and sets the values of the parameters. Then, it executes the statement to insert the values into the table.
  • validatePassword() method: This method validates the user’s password by comparing the given id and password with the data stored in the user’s table of the database. It takes two parameters: id and password. It creates a prepared statement and sets the value of the id parameter. Then, it executes the statement to get the corresponding row from the table. If the id and password match with the retrieved data, it returns true; otherwise, it returns false.
  • addQuestion() method: This method adds a new question along with its options and answers into the question table of the database. It takes three parameters: question, options, and answer. The options parameter is an array of four options. It creates a prepared statement and sets the values of the parameters. Then, it executes the statement to insert the values into the table.
  • delete() method: This method removes a record from the users or question table of the database using the given id and tableName parameters. If the tableName is a user, it removes the record from the users’ table using the userID. Otherwise, it removes the record from the question table using the QuestionID.
  • getQuestionAns() method: This method retrieves all the questions along with their options and answers from the question table of the database. It creates a prepared statement and executes it to get all the rows from the table. Then, it creates an ArrayList of Question objects using the retrieved data and returns it.
package org.projectgurukul;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.sqlite.SQLiteDataSource;

public class DataBase {
//	declaring connection and dataSource variables
    private static Connection conn;
    private static SQLiteDataSource ds;
    
//	initialize method to initialize the database with all the tables
    public static void dbInit() {
        ds = new SQLiteDataSource();
        
        try {
            ds = new SQLiteDataSource();
            ds.setUrl("jdbc:sqlite:QuizDB.db");
        } catch ( Exception e ) {
            e.printStackTrace();
            
            System.exit(0);
        }
        try {
        	 conn = ds.getConnection();
        	 
        	 Statement statement = conn.createStatement();
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS users (\n"
             		+ "  userID INTEGER PRIMARY KEY,\n"
             		+ "  username TEXT NOT NULL,\n"
             		+ "  email TEXT NOT NULL,\n"
             		+ "  password TEXT NOT NULL\n"
             		+ ");\n"
             		);
            
             statement.executeUpdate("CREATE TABLE IF NOT EXISTS question (\n"
             		+ "  QuestionID INTEGER PRIMARY KEY AUTOINCREMENT,\n"
             		+ "  Question TEXT,\n"
             		+ "  Option1 TEXT,\n"
             		+ "  Option2 TEXT,\n"
             		+ "  Option3 TEXT,\n"
             		+ "  Option4 TEXT,\n"
             		+ "  Answer TEXT);");
             
             
             
             
//           Closing statement and connection  
             statement.close();
        	 conn.close();
        	 
        }catch ( SQLException e ) {
            e.printStackTrace();
            System.exit( 0 );
        }
        finally {
            try {
                if (conn != null) {
                    conn.close();
                }
            }catch (SQLException e) {
                System.err.println(e);
              }
        
        }
    

    }
    
//	Method to add user into the database
    public static void addUser(int userID, String username, String email, String password) throws SQLException {
        conn = ds.getConnection();
        PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                                                    + "users(userID,username,email,password)"
                                                    + "VALUES(?,?,?,?)");
        ps.setInt(1, userID);
        ps.setString(2, username);
        ps.setString(3, email);
        ps.setString(4, password);
        
        
        ps.executeUpdate();
        ps.close();
        conn.close();
    }
    
//Method to validata the user id and password
    public static boolean validatePassword(String id, String password) throws SQLException {
        conn = ds.getConnection();
        String sql = "SELECT userID,password FROM users WHERE userID = ?;";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,id );
        ResultSet rs =  ps.executeQuery();
        
        
        if (id.equals(rs.getString("userID"))  && password.equals(rs.getString("password"))) {
            rs.close();
            ps.close();
            conn.close();
            return true;
        }
        
        rs.close();
        ps.close();
        conn.close();
        return false;		
    }
    
//	Method to add the Question,Answer into the database
    public static void addQuestion(String question,String[] options,String answer) throws SQLException {
        conn = ds.getConnection();
        PreparedStatement ps =conn.prepareStatement("INSERT INTO "
                                                    + "question(Question,Option1,Option2,Option3,Option4,Answer)"
                                                    + "VALUES(?,?,?,?,?,?)");
        ps.setString(1, question);
        ps.setString(2, options[0]);
        ps.setString(3, options[1]);
        ps.setString(4, options[2]);
        ps.setString(5, options[3]);
        ps.setString(6, answer);
        ps.executeUpdate();
        ps.close();
        conn.close();
    }

//	Method to remove any record from the user or the questions tables using the id and the given tableName
    public static void delete(String id,String tableName) throws SQLException {
        conn = ds.getConnection();
        String sql  ="DELETE FROM "+tableName+" WHERE QuestionID = ?";
        if(tableName.equals("users")) {
            sql = "DELETE FROM users WHERE userID = ?";
        }
        PreparedStatement ps =conn.prepareStatement(sql);

        ps.setInt(1, Integer.valueOf(id));

        ps.executeUpdate();
        ps.close();
        conn.close();
        
    }
    
//	Method to get question their option and their answer form the database
    public static ArrayList<Question> getQuestionAns() throws SQLException {
        conn = ds.getConnection();
        PreparedStatement ps =conn.prepareStatement("SELECT * FROM question");
        ResultSet rs = ps.executeQuery();
        ArrayList<Question> questions = new ArrayList<>();
        while (rs.next()) {
            String que = rs.getString("Question");
            String op1 = rs.getString("Option1");
            String op2 = rs.getString("Option2");
            String op3 = rs.getString("Option3");
            String op4 = rs.getString("Option4");
            String ans = rs.getString("Answer");
            questions.add(new Question(que, op1, op2, op3, op4, ans));
        }
        
        
        rs.close();
        ps.close();
        conn.close();
        
        return questions;
    }
    

}

ProfileChooser.java

package org.projectgurukul;

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import java.awt.Color;

public class ProfileChooser {

    private JFrame frmQuizApplication;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    ProfileChooser window = new ProfileChooser();
                    window.frmQuizApplication.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public ProfileChooser() {
        DataBase.dbInit();
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frmQuizApplication = new JFrame();
        frmQuizApplication.getContentPane().setBackground(new Color(246, 245, 244));
        frmQuizApplication.setTitle("Quiz Application By ProjectGurukul");
        frmQuizApplication.setBounds(100, 100, 440, 202);
        frmQuizApplication.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmQuizApplication.getContentPane().setLayout(null);
        
        JLabel lblWelcome = new JLabel("Welcome to Quiz Application");
        lblWelcome.setForeground(new Color(26, 95, 180));
        lblWelcome.setBounds(0, 0, 440, 35);
        lblWelcome.setFont(new Font("Jua", Font.BOLD, 20));
        lblWelcome.setHorizontalAlignment(SwingConstants.CENTER);
        frmQuizApplication.getContentPane().add(lblWelcome);
        
        JLabel lblInstruction = new JLabel("Please Select Login profile:");
        lblInstruction.setForeground(new Color(26, 95, 180));
        lblInstruction.setBounds(113, 12, 218, 52);
        frmQuizApplication.getContentPane().add(lblInstruction);
        
        JButton btnAdmin = new JButton("Admin");
        btnAdmin.setBounds(161, 50, 117, 50);
        btnAdmin.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                frmQuizApplication.dispose();
                AdminLogin adminLogin= new AdminLogin();
            }
            
        });
        frmQuizApplication.getContentPane().add(btnAdmin);
        
        JButton btnUser = new JButton("User");
        btnUser.setBounds(161, 105, 117, 50);
        btnUser.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                frmQuizApplication.dispose();
                UserLogin userLogin = new UserLogin();
                
            }
        });
        frmQuizApplication.getContentPane().add(btnUser);
    }
}

Questions.java

package org.projectgurukul;
public class Question {
    
    private String question;
    private String op1;
    private String op2;
    private String op3;
    private String op4;
    private String ans;
    
    public Question(String question, String op1, String op2, String op3, String op4, String ans) {
        super();
        this.question = question;
        this.op1 = op1;
        this.op2 = op2;
        this.op3 = op3;
        this.op4 = op4;
        this.ans = ans;
    }
    
    public String getQuestion() {
        return question;
    }

    public String getOp1() {
        return op1;
    }

    public String getOp2() {
        return op2;
    }

    public String getOp3() {
        return op3;
    }

    public String getOp4() {
        return op4;
    }

    public String getAns() {
        return ans;
    }

}

Quiz.java

package org.projectgurukul;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.BorderLayout;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class Quiz extends JFrame{
    ArrayList<Question> questions = null;
    private int count = 0;
    private int score = 0;
    public Quiz() {
        setTitle("Welcom to Quiz");
        setSize(600, 500);
        setVisible(true);
        
        startTimer(600);
        
        JPanel quePanel = new JPanel();
        getContentPane().add(quePanel, BorderLayout.NORTH);
        quePanel.setLayout(new BoxLayout(quePanel, BoxLayout.X_AXIS));
        
        
        JTextArea queTextArea = new JTextArea();
        queTextArea.setFont(new Font("Dialog", Font.BOLD, 20));
        queTextArea.setLineWrap(true);
        queTextArea.setWrapStyleWord(true);
        quePanel.add(queTextArea);
        
        JPanel optionsPanel = new JPanel();
        getContentPane().add(optionsPanel, BorderLayout.CENTER);
        optionsPanel.setLayout(new GridLayout(0, 2, 0, 0));
        
        optionsPanel.setLayout(new GridLayout(0, 2, 0, 0));
        JRadioButton rdbtnOp1 = new JRadioButton("Option 1");
        rdbtnOp1.setFont(new Font("Dialog", Font.BOLD, 20));
        rdbtnOp1.setHorizontalAlignment(SwingConstants.CENTER);
        rdbtnOp1.setVerticalAlignment(SwingConstants.CENTER);
        optionsPanel.add(rdbtnOp1);
        
        JRadioButton rdbtnOp2 = new JRadioButton("Option 2");
        rdbtnOp2.setFont(new Font("Dialog", Font.BOLD, 20));
        rdbtnOp2.setHorizontalAlignment(SwingConstants.CENTER);
        rdbtnOp2.setVerticalAlignment(SwingConstants.CENTER);
        optionsPanel.add(rdbtnOp2);
        
        JRadioButton rdbtnOp3 = new JRadioButton("Option 3");
        rdbtnOp3.setFont(new Font("Dialog", Font.BOLD, 20));
        rdbtnOp3.setHorizontalAlignment(SwingConstants.CENTER);
        rdbtnOp3.setVerticalAlignment(SwingConstants.CENTER);
        optionsPanel.add(rdbtnOp3);
        
        JRadioButton rdbtnOp4 = new JRadioButton("Option 4");
        rdbtnOp4.setFont(new Font("Dialog", Font.BOLD, 20));
        rdbtnOp4.setHorizontalAlignment(SwingConstants.CENTER);
        rdbtnOp4.setVerticalAlignment(SwingConstants.CENTER);
        optionsPanel.add(rdbtnOp4);
        
        ButtonGroup bg = new ButtonGroup();
        
        bg.add(rdbtnOp1);
        bg.add(rdbtnOp2);
        bg.add(rdbtnOp3);
        bg.add(rdbtnOp4);
        
        JPanel buttonsPanel = new JPanel();
        getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
        buttonsPanel.setLayout(new GridLayout(0, 1, 0, 0));
        try {
            questions =DataBase.getQuestionAns();
            queTextArea.setText(questions.get(count).getQuestion());
            rdbtnOp1.setText(questions.get(count).getOp1());
            rdbtnOp2.setText(questions.get(count).getOp2());
            rdbtnOp3.setText(questions.get(count).getOp3());
            rdbtnOp4.setText(questions.get(count).getOp4());
            
            
        } catch (SQLException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        
        JButton btnNext = new JButton("Next");
        btnNext.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                
                if(bg.getSelection() == null) {JOptionPane.showMessageDialog(quePanel,"Please select an Answer" );}
                else {
                        checkAnswer(count,bg);
                        count++;
                    if (questions.size() > count ) {
                        queTextArea.setText(questions.get(count).getQuestion());
                        rdbtnOp1.setText(questions.get(count).getOp1());
                        rdbtnOp2.setText(questions.get(count).getOp2());
                        rdbtnOp3.setText(questions.get(count).getOp3());
                        rdbtnOp4.setText(questions.get(count).getOp4());

                    }else {
                        displayScore();
                    }
                    
                }
                
            }
        });
        buttonsPanel.add(btnNext);
    }
    
//	Method which matches the answer with the selected options and increases the score
    private void checkAnswer(int count,ButtonGroup bg) {
        for (Enumeration<AbstractButton> buttons = bg.getElements(); buttons.hasMoreElements();) {
            AbstractButton button = buttons.nextElement();

            if (button.isSelected() && button.getText().equals(questions.get(count).getAns())) {
            	score++;
            }
        }
    }
    
//	Method to display the score at the end of the game
    private void displayScore() {
        
        dispose();
        JOptionPane.showMessageDialog(this, "Thanks for playing the Quiz by ProjectGurukul\n Your Score was: "+score,"Quiz by ProjectGurukul",JOptionPane.PLAIN_MESSAGE);
    }
    
//	Method to add and start the timer for the entire quiz
    private void startTimer(int timeInSecs) {
        JLabel timerLabel = new JLabel(String.format("%02d:%02d", timeInSecs / 60, timeInSecs % 60));
        timerLabel.setFont(new Font("Dialog", Font.BOLD, 20));
        timerLabel.setHorizontalAlignment(SwingConstants.CENTER);
        getContentPane().add(timerLabel, BorderLayout.EAST);

        Timer timer = new Timer(1000, new ActionListener() {
            int timeLeft = timeInSecs;

            @Override
            public void actionPerformed(ActionEvent e) {
                if (timeLeft > 0) {
                    timeLeft--;
                    timerLabel.setText(String.format("%02d:%02d", timeLeft / 60, timeLeft % 60));
                } else {
                    ((Timer) e.getSource()).stop();
                    displayScore();
                    
                }
            }
        });

        timer.start();
    }

}

Register.java

package org.projectgurukul;

import javax.swing.JFrame;
import java.awt.GridLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;

public class Register {
    private JFrame frame;
    private JTextField userIdField;
    private JLabel lblName;
    private JTextField nameField;
    private JLabel lblemail;
    private JTextField emailField;
    private JLabel lblPassword;
    private JPasswordField passwordField;
    private JButton btnBack;
    private JButton btnRegister;
    
    public Register() {
        initialilze();
    }

    private void initialilze() {
        
        frame = new JFrame();
        frame.setBounds(100, 100, 598, 372);
        frame.setTitle("User Registration");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new GridLayout(0, 2, 5, 5));
        
        JLabel lblId = new JLabel("User ID:");
        frame.getContentPane().add(lblId);
        
        userIdField = new JTextField();
        frame.getContentPane().add(userIdField);
        userIdField.setColumns(10);
        
        lblName = new JLabel("Name:");
        frame.getContentPane().add(lblName);
        
        nameField = new JTextField();
        nameField.setColumns(10);
        frame.getContentPane().add(nameField);
        
        lblemail = new JLabel("Email:");
        frame.getContentPane().add(lblemail);
        
        emailField = new JTextField();
        emailField.setColumns(10);
        frame.getContentPane().add(emailField);
        
        lblPassword = new JLabel("Password");
        frame.getContentPane().add(lblPassword);
        
        passwordField = new JPasswordField();
        frame.getContentPane().add(passwordField);
        
        btnBack = new JButton("Back");
        btnBack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
                UserLogin userLogin = new UserLogin();
            }
        });
        frame.getContentPane().add(btnBack);
        
        btnRegister = new JButton("Register");
        btnRegister.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    DataBase.addUser(Integer.valueOf(userIdField.getText()), nameField.getText(), emailField.getText(), new String(passwordField.getPassword()));
                    JOptionPane.showMessageDialog(btnRegister, "User Added Successfully", "Success", JOptionPane.INFORMATION_MESSAGE);

                } catch (SQLException e1) {
                    JOptionPane.showMessageDialog(btnRegister, "Can't Add User\n"+e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    e1.printStackTrace();
                }
            }
        });
        frame.getContentPane().add(btnRegister);
        frame.setVisible(true);
    }
}

UserLogin.java

package org.projectgurukul;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.awt.event.ActionEvent;

public class UserLogin {
    private JFrame frame;
    private JTextField idField;
    private JPasswordField passwordField;

    public UserLogin() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setTitle("User Login");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.getContentPane().setLayout(null);
        
        JLabel lblId = new JLabel("ID:");
        lblId.setBounds(0, 12, 173, 36);
        frame.getContentPane().add(lblId);
        
        idField = new JTextField();
        idField.setBounds(222, 13, 184, 36);
        frame.getContentPane().add(idField);
        idField.setColumns(10);
        
        JLabel lblPassword = new JLabel("Password");
        lblPassword.setBounds(0, 79, 173, 36);
        frame.getContentPane().add(lblPassword);
        
        passwordField = new JPasswordField();
        passwordField.setBounds(220, 80, 184, 36);
        frame.getContentPane().add(passwordField);
        
        JButton btnLogin = new JButton("Login");
        btnLogin.setBounds(145, 126, 150, 50);
        btnLogin.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                
                try {
                    if (DataBase.validatePassword(idField.getText(),new String(passwordField.getPassword()))) {
                        frame.dispose();
                        Quiz quiz = new Quiz();
                    } else {
                        JOptionPane.showMessageDialog(btnLogin, "ID or Password does not match","Invalid ID/Password",JOptionPane.ERROR_MESSAGE);
                    }
                } catch (SQLException e1) {
                    e1.printStackTrace();
                }
            }
        });
        frame.getContentPane().add(btnLogin);
        
        JButton btnRegister = new JButton("Register  ");
        btnRegister.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
                Register register = new Register();
            }
        });
        
        JLabel lblNewUser = new JLabel("New User?");
        lblNewUser.setBounds(150, 175, 173, 36);
        frame.getContentPane().add(lblNewUser);
        btnRegister.setBounds(145, 208, 150, 50);
        frame.getContentPane().add(btnRegister);
        frame.setVisible(true);
    }
}

Java Quiz Application Output

quiz application output

java quiz application output

quiz application score output

Summary:

At the end of this Java quiz application project, you will have gained the necessary skills and knowledge to develop a fully functional quiz application using Java Swing and SQLite database. You will have learned how to create a user-friendly GUI for the application, set up an SQLite database to store quiz questions and answers and implement essential functionalities such as score tracking and quiz timer.

Additionally, you will have developed an admin panel that allows for the addition and deletion of questions and users. With the knowledge gained from this tutorial, you will be able to create a quiz application.

Leave a Reply

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