SlideShare a Scribd company logo
1 of 39
Download to read offline
Java Quiz Application –
Compete, and Dominate
Java’s Mysteries!
In this article, we will discuss Java Quiz Application. 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.get
Text()};
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 Questionn"+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 Questionn"+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 NULLn"
+ ");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 ProjectGurukuln
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 Usern"+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);
}
}
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.

More Related Content

What's hot

Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Kanika Gera
 
GlassFish in Production Environments
GlassFish in Production EnvironmentsGlassFish in Production Environments
GlassFish in Production EnvironmentsBruno Borges
 
Clean architecture
Clean architectureClean architecture
Clean architectureLieven Doclo
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...Edureka!
 
Java 9 Module System Introduction
Java 9 Module System IntroductionJava 9 Module System Introduction
Java 9 Module System IntroductionDan Stine
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WSKatrien Verbert
 
Front end-security
Front end-securityFront end-security
Front end-securityMiao Siyu
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Managing Complex UI using xState
Managing Complex UI using xStateManaging Complex UI using xState
Managing Complex UI using xStateXavier Lozinguez
 
Basics of Vue.js 2019
Basics of Vue.js 2019Basics of Vue.js 2019
Basics of Vue.js 2019Paul Bele
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSRafael Casuso Romate
 

What's hot (20)

Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction Node.Js: Basics Concepts and Introduction
Node.Js: Basics Concepts and Introduction
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
GlassFish in Production Environments
GlassFish in Production EnvironmentsGlassFish in Production Environments
GlassFish in Production Environments
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Scalable web architecture
Scalable web architectureScalable web architecture
Scalable web architecture
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js +  Expres...
Node.js Express Tutorial | Node.js Tutorial For Beginners | Node.js + Expres...
 
Java 9 Module System Introduction
Java 9 Module System IntroductionJava 9 Module System Introduction
Java 9 Module System Introduction
 
What's new in Java 11
What's new in Java 11What's new in Java 11
What's new in Java 11
 
Using Java to implement SOAP Web Services: JAX-WS
Using Java to implement SOAP Web Services: JAX-WS�Using Java to implement SOAP Web Services: JAX-WS�
Using Java to implement SOAP Web Services: JAX-WS
 
Java 11 to 17 : What's new !?
Java 11 to 17 : What's new !?Java 11 to 17 : What's new !?
Java 11 to 17 : What's new !?
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Front end-security
Front end-securityFront end-security
Front end-security
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Managing Complex UI using xState
Managing Complex UI using xStateManaging Complex UI using xState
Managing Complex UI using xState
 
Basics of Vue.js 2019
Basics of Vue.js 2019Basics of Vue.js 2019
Basics of Vue.js 2019
 
Solid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJSSolid NodeJS with TypeScript, Jest & NestJS
Solid NodeJS with TypeScript, Jest & NestJS
 
Java and XML
Java and XMLJava and XML
Java and XML
 

Similar to Java Quiz Application .pdf

How to use sq lite with java using net beans
How to use sq lite with java using net beansHow to use sq lite with java using net beans
How to use sq lite with java using net beansAravindharamanan S
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenSony Suci
 
College management system.pptx
College management system.pptxCollege management system.pptx
College management system.pptxManujArora3
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxBOSC Tech Labs
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 
Web components with java by Haijian Wang
Web components with java by Haijian WangWeb components with java by Haijian Wang
Web components with java by Haijian WangGWTcon
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteRavi Bhadauria
 
Сергей Больщиков "Protractor Tips & Tricks"
Сергей Больщиков "Protractor Tips & Tricks"Сергей Больщиков "Protractor Tips & Tricks"
Сергей Больщиков "Protractor Tips & Tricks"Fwdays
 
How to develop frontend quiz app using vue js
How to develop frontend quiz app using vue jsHow to develop frontend quiz app using vue js
How to develop frontend quiz app using vue jsKaty Slemon
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for ProductivityDavid Noble
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptxvishal choudhary
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CNjojule
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MySteve McMahon
 
Top 45 jQuery Interview Questions and Answers | Edureka
Top 45 jQuery Interview Questions and Answers | EdurekaTop 45 jQuery Interview Questions and Answers | Edureka
Top 45 jQuery Interview Questions and Answers | EdurekaEdureka!
 

Similar to Java Quiz Application .pdf (20)

How to use sq lite with java using net beans
How to use sq lite with java using net beansHow to use sq lite with java using net beans
How to use sq lite with java using net beans
 
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) kerenTutorial mvc (pelajari ini jika ingin tahu mvc) keren
Tutorial mvc (pelajari ini jika ingin tahu mvc) keren
 
College management system.pptx
College management system.pptxCollege management system.pptx
College management system.pptx
 
Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
 
Chapter6 database connectivity
Chapter6 database connectivityChapter6 database connectivity
Chapter6 database connectivity
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
D3_Tuto_GD
D3_Tuto_GDD3_Tuto_GD
D3_Tuto_GD
 
D3_Tuto_GD
D3_Tuto_GDD3_Tuto_GD
D3_Tuto_GD
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
Web components with java by Haijian Wang
Web components with java by Haijian WangWeb components with java by Haijian Wang
Web components with java by Haijian Wang
 
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia InstituteMVC Design Pattern in JavaScript by ADMEC Multimedia Institute
MVC Design Pattern in JavaScript by ADMEC Multimedia Institute
 
Сергей Больщиков "Protractor Tips & Tricks"
Сергей Больщиков "Protractor Tips & Tricks"Сергей Больщиков "Protractor Tips & Tricks"
Сергей Больщиков "Protractor Tips & Tricks"
 
How to develop frontend quiz app using vue js
How to develop frontend quiz app using vue jsHow to develop frontend quiz app using vue js
How to develop frontend quiz app using vue js
 
Java Code Generation for Productivity
Java Code Generation for ProductivityJava Code Generation for Productivity
Java Code Generation for Productivity
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Vaadin 7 CN
Vaadin 7 CNVaadin 7 CN
Vaadin 7 CN
 
Overlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh MyOverlays, Accordions & Tabs, Oh My
Overlays, Accordions & Tabs, Oh My
 
Top 45 jQuery Interview Questions and Answers | Edureka
Top 45 jQuery Interview Questions and Answers | EdurekaTop 45 jQuery Interview Questions and Answers | Edureka
Top 45 jQuery Interview Questions and Answers | Edureka
 

More from SudhanshiBakre1

Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdfSudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfSudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdfSudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdfSudhanshiBakre1
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfSudhanshiBakre1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdfSudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdfSudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfSudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfSudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfSudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfSudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfSudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
Collections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdfCollections in Python - Where Data Finds Its Perfect Home.pdf
Collections in Python - Where Data Finds Its Perfect Home.pdf
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 

Recently uploaded

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 

Java Quiz Application .pdf

  • 1. Java Quiz Application – Compete, and Dominate Java’s Mysteries! In this article, we will discuss Java Quiz Application. 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.
  • 2. 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
  • 3. 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.
  • 4. 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();
  • 5. } /** * 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);
  • 6. 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;
  • 7. 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);
  • 8. 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();
  • 9. 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();
  • 10. 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.get Text()}; 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 Questionn"+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 {
  • 11. DataBase.delete(remIDfield.getText(), (String)comboBox.getSelectedItem()); JOptionPane.showMessageDialog(btnAddQue,"Deleted Sucessfully", "Success", JOptionPane.INFORMATION_MESSAGE); } catch (SQLException e1) { JOptionPane.showMessageDialog(btnAddQue,"Delete Questionn"+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); } });
  • 12. 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);
  • 13. 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
  • 14. 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;
  • 15. 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"
  • 16. + " email TEXT NOT NULL,n" + " password TEXT NOT NULLn" + ");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();
  • 17. } }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 {
  • 18. 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(?,?,?,?,?,?)");
  • 19. 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();
  • 20. } // 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; } }
  • 21. 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);
  • 22. } 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);
  • 23. 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() {
  • 24. @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;
  • 25. 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; }
  • 26. } 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;
  • 27. 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");
  • 28. 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);
  • 29. 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++;
  • 30. 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++; } }
  • 31. } // Method to display the score at the end of the game private void displayScore() { dispose(); JOptionPane.showMessageDialog(this, "Thanks for playing the Quiz by ProjectGurukuln 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();
  • 32. } } }); 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;
  • 33. 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);
  • 34. 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) {
  • 35. 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 Usern"+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;
  • 36. 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);
  • 37. 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); }
  • 38. } 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); } } Summary:
  • 39. 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.