Advance Java Micro
Advance Java Micro
JONDHALE POLYTECHNIC
DEPARTMENT:COMPUTER
SEMESTER:5TH
YEAR: 2024-25
PREPARED BY:
1. SANSKRUTI NILE [1503]
1
Maharashtra State Board of Technical Education
Certificate
Seal of institute
2
ACKNOWLEDGMENT
3
ABSTRACT
This project, titled "MCQ Test Platform For Java," is designed to help users test
their knowledge through multiple-choice questions (MCQs) on various topics. It
offers a user-friendly interface with functionalities like user account creation,
secure login, and chapter-based MCQ practice. The system consists of six
chapters, . After successfully logging in, users can select a chapter and attempt
all questions displayed at once in a scrollable panel, providing a seamless
quiz-taking experience.
The system checks user inputs and calculates the score upon submission. This
Java application integrates essential GUI components using Swing for layout
management and form handling. It efficiently tracks users' progress and allows
for the creation of multiple accounts, ensuring personalized experiences. The
program's back-end ensures proper validation of user credentials and stores
account information for secure access.
4
ACTION PLAN
Sr. Wee Details of activity Planned Planned Name of Responsible
No. k Start date Finish Team
date Members
1 1 & Discussion and finalization of the
2 topic. 1\8\24 10\8\24 sanskruti
3 4 Literature review
18\8\24 24\8\24 sanskruti
8 9 Analysis/execution of collected
data/information and Preparation of 22\9\24 28\924 sanskruti
prototypes/drawings/charts/graphs/
tables/models/circuits/programs
etc.
9 10 Compilation of contents of project
29\9\24 5\10\24 sanskruti
5
INDEX
3. Design approach 9
5. Source code 10-25
6. Overview of code 26
7. Output 27-28
8. Future Scope 29
8. Conclusion 30
10. Reference 31
6
INTRODUCTION
The application employs a graphical user interface (GUI) built using Swing,
ensuring that it is both intuitive and user-friendly. After logging in, users are
presented with a scrollable interface that displays all questions at once, allowing
for a comprehensive review of the material. Each question includes radio
buttons for selecting answers, promoting efficient input and usability. Upon
submission, users receive immediate feedback with their score, enhancing the
learning experience. This project not only showcases practical skills in
Advanced Java but also emphasizes the importance of creating functional,
real-world applications that facilitate learning and knowledge assessment. By
implementing user authentication, the project underscores the significance of
data security and user management in software development.
7
REQUIREMENT ANALYSIS AND SYSTEM SPECIFICATION
8
DESIGN APPROACH
The MCQ Test Platform for Java is designed with a user-centric approach,
emphasizing simplicity, accessibility, and engagement. The application is built
using Java's Swing framework, providing a graphical user interface (GUI) that
is intuitive and easy to navigate. The design consists of two main
functionalities: account management and a multiple-choice question (MCQ)
testing system. The account management feature allows users to create and log
in to their accounts, while the MCQ testing feature enables users to select
chapters and answer questions related to those topics. Each chapter contains ten
questions, ensuring comprehensive coverage of the subject matter.
To enhance usability, the project integrates a scrollable interface for the question
display, allowing users to view all questions at once, thereby improving
engagement and reducing navigation complexity. This design choice caters to
users' preference for a holistic view of their progress during the test. The
implementation of radio buttons for selecting answers simplifies the interaction
process, making it straightforward for users to submit their responses. Overall,
the design approach prioritizes user experience while leveraging Java's
capabilities to create a functional and educational tool for mastering Java
concepts through self-assessment.
9
SOURCE CODE
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
10
"10. Which method is used to add components to a frame?\nA. addComponent()\nB.
add()\nC. insert()\nD. append()"
},
{
"1. What does Swing provide?\nA. Lightweight components\nB. Heavyweight
components\nC. Only AWT components\nD. No components",
"2. Which class is a top-level container in Swing?\nA. JFrame\nB. Frame\nC.
Window\nD. JPanel",
"3. Which method is used to create a JButton?\nA. new JButton()\nB.
JButton.create()\nC. JButton()\nD. createButton()",
"4. What is the default layout manager for JPanel?\nA. FlowLayout\nB.
BorderLayout\nC. GridLayout\nD. BoxLayout",
"5. How do you change the background color of a JPanel?\nA.
setBackgroundColor()\nB. setBackground()\nC. changeColor()\nD. colorBackground()",
"6. What is the purpose of the JLabel class?\nA. To display text\nB. To create
buttons\nC. To hold input\nD. To layout components",
"7. Which method is used to get the text from a JTextField?\nA. getTextField()\nB.
getText()\nC. retrieveText()\nD. fetchText()",
"8. What is the function of JRadioButton?\nA. To create multiple selections\nB. To
allow single selections\nC. To display images\nD. To hold text",
"9. How do you group JRadioButton objects?\nA. By using a ButtonGroup\nB. By
using a JPanel\nC. By using a layout manager\nD. By using a checkbox",
"10. What is the main advantage of using Swing over AWT?\nA. Swing is faster\nB.
Swing is lightweight\nC. AWT is better\nD. Swing has no advantages"
},
{
"1. What is an event listener?\nA. A component that listens to events\nB. A part of the
GUI\nC. A method in AWT\nD. An object that generates events",
"2. How do you add an ActionListener to a button?\nA. button.addListener()\nB.
button.addActionListener()\nC. button.listener()\nD. button.attachListener()",
"3. What is the purpose of the actionPerformed method?\nA. To trigger an event\nB.
To handle events\nC. To create a button\nD. To show messages",
"4. Which interface is used for handling mouse events?\nA. MouseListener\nB.
MouseAdapter\nC. MouseEvent\nD. ActionListener",
"5. What is a mouse click considered?\nA. A single event\nB. A double event\nC. A
compound event\nD. A sequential event",
"6. How do you remove an event listener?\nA. removeListener()\nB.
removeActionListener()\nC. detachListener()\nD. deleteListener()",
"7. What is the difference between an event and an event source?\nA. An event is the
source of actions\nB. An event source generates events\nC. An event is a method\nD. An
event source is not needed",
"8. What method do you use to trigger an event?\nA. fire()\nB. trigger()\nC.
action()\nD. notify()",
11
"9. What are the two types of events in AWT?\nA. Mouse and keyboard\nB. Action
and state\nC. User and system\nD. Timer and action",
"10. How do you make a component focusable?\nA. setFocusable()\nB.
setFocus()\nC. requestFocus()\nD. enableFocus()"
},
{
"1. What is a TCP socket?\nA. A connection-oriented protocol\nB. A connectionless
protocol\nC. A GUI component\nD. None of the above",
"2. How do you create a Socket object in Java?\nA. new Socket()\nB.
Socket.create()\nC. new SocketObject()\nD. createSocket()",
"3. What is the purpose of the ServerSocket class?\nA. To create a server\nB. To send
data\nC. To listen for incoming connections\nD. To close connections",
"4. How do you establish a connection to a server?\nA. connect()\nB. open()\nC.
accept()\nD. Socket.connect()",
"5. What is the difference between TCP and UDP?\nA. TCP is faster\nB. UDP is
connection-oriented\nC. TCP is reliable\nD. No difference",
"6. How do you send data through a socket?\nA. write()\nB. send()\nC. transmit()\nD.
push()",
"7. What method do you use to close a socket?\nA. closeSocket()\nB. terminate()\nC.
close()\nD. end()",
"8. How do you receive data through a socket?\nA. read()\nB. getData()\nC.
retrieve()\nD. accept()",
"9. What is the purpose of the InputStream class?\nA. To read data\nB. To write
data\nC. To process events\nD. To create connections",
"10. How do you handle exceptions in socket programming?\nA. Use try-catch\nB.
Use throws\nC. Ignore them\nD. Log them"
},
{
"1. What is JDBC?\nA. Java Database Connectivity\nB. Java Data Connection\nC.
Java Database Communication\nD. None of the above",
"2. Which driver is used for MySQL?\nA. MySQLDriver\nB.
com.mysql.jdbc.Driver\nC. MySQLConnector\nD. java.sql.Driver",
"3. How do you establish a connection to a database?\nA.
DriverManager.getConnection()\nB. ConnectionManager.connect()\nC.
Database.connect()\nD. connectDatabase()",
"4. What method do you use to execute a query?\nA. executeQuery()\nB.
runQuery()\nC. execute()\nD. query()",
"5. How do you retrieve data from a ResultSet?\nA. getData()\nB. fetch()\nC.
retrieve()\nD. get()",
"6. What is a PreparedStatement?\nA. A pre-compiled SQL statement\nB. A type of
ResultSet\nC. A method for executing statements\nD. None of the above",
"7. What is the difference between Statement and PreparedStatement?\nA. Statement
is faster\nB. PreparedStatement is pre-compiled\nC. Both are the same\nD. None of the
above",
12
"8. How do you handle SQL exceptions?\nA. Use try-catch\nB. Use throws\nC.
Ignore them\nD. Log them",
"9. What method is used to close a Connection?\nA. closeConnection()\nB.
terminate()\nC. close()\nD. end()",
"10. What does CRUD stand for?\nA. Create, Read, Update, Delete\nB. Create,
Retrieve, Update, Delete\nC. Create, Read, Upload, Delete\nD. Create, Read, Update, Drop"
},
{
"1. What does API stand for?\nA. Application Programming Interface\nB.
Application Protocol Interface\nC. Application Performance Indicator\nD. None of the
above",
"2. Which HTTP method is used to retrieve data?\nA. POST\nB. GET\nC. PUT\nD.
DELETE",
"3. What is REST?\nA. Representational State Transfer\nB. Remote Event State
Transfer\nC. Remote Service Transfer\nD. None of the above",
"4. What does JSON stand for?\nA. JavaScript Object Notation\nB. JavaScript Object
Notation\nC. JavaScript Open Notation\nD. None of the above",
"5. What is the purpose of an API?\nA. To create databases\nB. To provide a way for
applications to communicate\nC. To manage user interfaces\nD. None of the above",
"6. What is a web service?\nA. A software system designed to support interoperable
machine-to-machine interaction\nB. A service that is hosted on the web\nC. A database
management system\nD. None of the above",
"7. How is data usually formatted in an API response?\nA. XML\nB. JSON\nC. Both
A and B\nD. None of the above",
"8. What is an endpoint?\nA. The URL at which an API can be accessed\nB. A
method in a class\nC. A type of response\nD. None of the above",
"9. What is an API key?\nA. A secret token for authentication\nB. A public key for
encryption\nC. A unique identifier for a user\nD. None of the above",
"10. What is the status code for a successful HTTP request?\nA. 404\nB. 200\nC.
500\nD. 301"
}
};
13
private static final String[] CHAPTERS = {
"Chapter 1: AWT",
"Chapter 2: Swing",
"Chapter 3: Event Handling",
"Chapter 4: Sockets",
"Chapter 5: JDBC",
"Chapter 6: APIs"
};
14
// new java.net.URL[] { new java.io.File(driverPath).toURI().toURL() },
// TestConnection.class.getClassLoader()
// );
} catch (Exception e) {
System.out.println("Error loading driver: " + e.getMessage());
e.printStackTrace();
return;
}
SwingUtilities.invokeLater(() -> {
frame = new JFrame("MCQ Test Platform");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 800);
frame.setLocationRelativeTo(null);
showLogin();
frame.setVisible(true);
});
}
gbc.gridx = 0; gbc.gridy = 0;
panel.add(new JLabel("User ID:"), gbc);
gbc.gridx = 1;
panel.add(userIdField, gbc);
gbc.gridx = 0; gbc.gridy = 1;
panel.add(new JLabel("Password:"), gbc);
gbc.gridx = 1;
panel.add(passwordField, gbc);
15
loginButton.addActionListener(e -> {
String userId = userIdField.getText().trim();
String password = new String(passwordField.getPassword());
try {
if (validateLogin(userId, password)) {
currentUser = userId;
if (!userScores.containsKey(userId)) {
userScores.put(userId, new HashMap<>());
}
loadUserScores(userId);
showChapterSelection();
} else {
JOptionPane.showMessageDialog(frame,
"Invalid credentials. Please try again.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame,
"Database error: " + ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
});
frame.setContentPane(panel);
frame.revalidate();
}
16
pstmt.setString(2, password);
return pstmt.executeQuery().next();
}
}
ResultSet rs = pstmt.executeQuery();
Map<String, Integer> scores = userScores.get(userId);
while (rs.next()) {
scores.put(rs.getString("chapter"), rs.getInt("score"));
}
}
}
gbc.gridx = 0; gbc.gridy = 1;
panel.add(new JLabel("Email:"), gbc);
gbc.gridx = 1;
panel.add(emailField, gbc);
17
gbc.gridx = 0; gbc.gridy = 2;
panel.add(new JLabel("Phone Number:"), gbc);
gbc.gridx = 1;
panel.add(phoneField, gbc);
gbc.gridx = 0; gbc.gridy = 3;
panel.add(new JLabel("User ID:"), gbc);
gbc.gridx = 1;
panel.add(userIdField, gbc);
gbc.gridx = 0; gbc.gridy = 4;
panel.add(new JLabel("Password:"), gbc);
gbc.gridx = 1;
panel.add(passwordField, gbc);
gbc.gridx = 0; gbc.gridy = 5;
panel.add(new JLabel("Confirm Password:"), gbc);
gbc.gridx = 1;
panel.add(confirmPasswordField, gbc);
createButton.addActionListener(e -> {
String fullName = fullNameField.getText().trim();
String email = emailField.getText().trim();
String phone = phoneField.getText().trim();
String userId = userIdField.getText().trim();
String password = new String(passwordField.getPassword());
String confirmPass = new String(confirmPasswordField.getPassword());
// Validation
if (fullName.isEmpty() || email.isEmpty() || phone.isEmpty() ||
userId.isEmpty() || password.isEmpty()) {
JOptionPane.showMessageDialog(frame,
"All fields are required.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (!email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
JOptionPane.showMessageDialog(frame,
"Please enter a valid email address.",
18
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (!phone.matches("\\d{10}")) {
JOptionPane.showMessageDialog(frame,
"Please enter a valid 10-digit phone number.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
if (!password.equals(confirmPass)) {
JOptionPane.showMessageDialog(frame,
"Passwords do not match.",
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
createNewUser(userId, password, fullName, email, phone);
JOptionPane.showMessageDialog(frame,
"Account created successfully! You can now log in.",
"Success",
JOptionPane.INFORMATION_MESSAGE);
showLogin();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame,
"Error creating account: " + ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
});
frame.setContentPane(panel);
19
frame.revalidate();
}
pstmt.executeUpdate();
}
}
20
"Error loading user profile: " + ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
chapterPanel.add(chapterButton);
}
frame.setContentPane(mainPanel);
frame.revalidate();
}
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
return new UserProfile(
rs.getString("full_name"),
rs.getString("email"),
rs.getString("phone"),
rs.getString("password")
);
21
}
throw new SQLException("User profile not found");
}
}
private static void startQuiz(String chapter) {
int chapterIndex = getChapterIndex(chapter);
questionResponses = new ArrayList<>();
buttonPanel.add(submitButton);
buttonPanel.add(backButton);
22
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
frame.setContentPane(mainPanel);
frame.revalidate();
}
if (selectedAnswer == null) {
sb.append("Q").append(i + 1).append(": Not answered\n");
} else if (answers[i].equals(selectedAnswer)) {
score++;
sb.append("Q").append(i + 1).append(": Correct\n");
} else {
sb.append("Q").append(i + 1).append(": Incorrect. Correct answer is
").append(answers[i]).append("\n");
}
}
23
try {
saveScore(currentUser, chapter, score);
userScores.get(currentUser).put(chapter, score);
JOptionPane.showMessageDialog(frame, sb.toString(), "Quiz Results",
JOptionPane.INFORMATION_MESSAGE);
showChapterSelection();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(frame,
"Error saving score: " + ex.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
private static void saveScore(String userId, String chapter, int score) throws SQLException
{
try (Connection conn = getConnection()) {
// First check if a score already exists
String checkSql = "SELECT id FROM scores WHERE user_id = ? AND chapter =
?";
PreparedStatement checkStmt = conn.prepareStatement(checkSql);
checkStmt.setString(1, userId);
checkStmt.setString(2, chapter);
ResultSet rs = checkStmt.executeQuery();
if (rs.next()) {
// Update existing score
String updateSql = "UPDATE scores SET score = ?, attempt_date =
CURRENT_TIMESTAMP WHERE user_id = ? AND chapter = ?";
PreparedStatement updateStmt = conn.prepareStatement(updateSql);
updateStmt.setInt(1, score);
updateStmt.setString(2, userId);
updateStmt.setString(3, chapter);
updateStmt.executeUpdate();
} else {
// Insert new score
String insertSql = "INSERT INTO scores (user_id, chapter, score) VALUES (?, ?,
?)";
PreparedStatement insertStmt = conn.prepareStatement(insertSql);
insertStmt.setString(1, userId);
insertStmt.setString(2, chapter);
insertStmt.setInt(3, score);
insertStmt.executeUpdate();
24
}
}
}
25
OVERVIEW OF CODE
1. Data Definitions:
○ QUESTIONS: Arrays of questions for each chapter.
○ ANSWERS: Corresponding correct answers for each question.
2. Main Application (MCQApp):
○ The main method initializes the GUI.
○ Components include JTextField for username, JPasswordField for
password, and buttons for creating accounts and logging in.
3. Action Listeners:
○ CreateAccountListener: Handles account creation, ensuring the
username and password fields are filled and checking for existing
usernames.
○ LoginListener: Validates user credentials and proceeds to the quiz
if successful.
4. Quiz Functionality:
○ showPracticeOptions(): Presents the user with chapter options and
displays corresponding questions in a scrollable dialog.
○ SubmitListener: Evaluates the answers when the user submits their
responses, displaying the final score.
How It Works
26
OUTPUT
Account creation :-
Login :-
27
Mcq list :-
Submit process:-
28
FUTURE SCOPE
The future scope of your MCQ Test Platform for Java can be significantly
expanded to enhance functionality and user experience. Consider implementing
user accounts and profiles for personalized tracking of progress and
performance. A dynamic question management system could allow
administrators to easily update the question bank, while adaptive learning
features could offer personalized quizzes based on user performance. Integrating
detailed reporting and analytics would provide insights into user strengths and
weaknesses, while supporting multimedia content can create engaging quizzes.
Developing a mobile application could improve accessibility, and gamification
elements like leaderboards and badges could boost user engagement.
Incorporating social features and integration with Learning Management
Systems (LMS) can broaden the platform’s appeal, while ensuring accessibility
and multi-language support would make it more inclusive. Lastly, a robust
feedback mechanism for users and regular data backups would ensure a
continuously improving and secure platform. These enhancements can
transform your application into a comprehensive educational tool that caters to a
diverse audience and promotes an interactive learning experience.
29
CONCLUSION
30
REFERENCE
● www.google.com
● www.studoc.com
● www.greeksforgreeks.com
● www.scrib.com
● www.wordpress.com
31