Previouslywe seen how to create Simple Registration Form with GUI Connection withMySQL Database : SimpleRegistration Form using JAVA Swing - Step2 (Connecting GUI with MySQL Databaseusing JDBC)
Here weare going to create an Application of Objective Test, in this application weshow Questions with its options one by one, options will load dynamically. Wegetting our questions and its options through MySQL database.
This Javaprogram needs some important packages:
· java.sql.Connection;
· java.sql.ResultSet;
· java.sql.Statement;
For connecting java application with theMySQL database, you need to follow steps to perform database connectivity: ( In this example weare using MySQL as the database. So we need to know following informations forthe MySQL database ):
· Driverclass: The driver class for the mysql database iscom.mysql.jdbc.Driver.
· ConnectionURL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/projectwhere jdbc is the API, mysql is the database, localhost is the server name onwhich mysql is running, we may also use IP address, 3306 is the port number andproject is the database name. We may use any database, in such case, you needto replace the project with your database name.
· Username: Thedefault username for the mysql database is root.
· Password: Passwordis given by the user at the time of installing the mysql database. In thisexample, we are going to use root as the password.
[ Toconnect java application with the MySQL database mysqlconnector.jar file is
required to be loaded.]
In Database our table Structure will be like this:

Java Codes:
DynamicTest.java
import java.awt.Color;
import java.awt.Component;import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.Connection;
import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.Statement; import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton; import javax.swing.border.Border; import javax.swing.border.TitledBorder;
@SuppressWarnings("serial")
public class DynamicTest extends JFrame implements ActionListener, ItemListener{
int frameHight=600,frameWidth=700; JFrame childFrame; JPanel questionPanel,optionPanel,buttonPanel,resultPanel; JButton previousButton,nextButton,childPreviousButton,childNextButton,
resultButton,describeResultButton,restart,childRestart; JLabel title,questionLabel,totalQuestion,attemptedQuestion,
unattemptedQuestion,correct,incorrect;
Connection con; Statement statement; String[] optionString=null; ResultSet questionRst; JRadioButton[] optionsButton = null;
ButtonGroup buttonGroup = new ButtonGroup(); HashMap<Long,String> map = new HashMap<Long,String>();
int count=0, nor=0, childCount=0;
String correctOption=null;
ImageIcon icon,icon1,icon3;
DynamicTest(){
super("Objective Questions"); setSize(frameWidth,frameHight);
setLayout(null);
try{
//calling connect() method
connect();
//fetching all rows from table
questionRst = statement.executeQuery("select * from objectivetest");
//fetch the last record of the table
questionRst.last();
nor=questionRst.getRow();
title = new JLabel("Objective Test");
title.setBounds(frameHight/2,20,200,30); title.setFont(new Font("Arial", Font.BOLD,20));
add(title);
questionPanel = new JPanel();
questionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
questionPanel.setBounds(frameWidth/9,90,550,50);
questionLabel = new JLabel("..............................");
questionPanel.add(questionLabel);
add(questionPanel);
optionPanel = new JPanel();
optionPanel.setLayout(new GridLayout(4,2));
optionPanel.setBounds(frameWidth/7,150,550,160); add(optionPanel);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(2,2,5,5)); buttonPanel.setBounds(frameWidth/9,320,550,70); previousButton = new JButton("Previous");
previousButton.addActionListener(this);
buttonPanel.add(previousButton);
nextButton = new JButton("Next");
nextButton.addActionListener(this);
buttonPanel.add(nextButton);
resultButton = new JButton("Result");
resultButton = new JButton("Result");
resultButton.addActionListener(this);
buttonPanel.add(resultButton);
describeResultButton = new JButton("Show Result Discription");
describeResultButton.addActionListener(this);
buttonPanel.add(describeResultButton);
describeResultButton.setEnabled(false);
add(buttonPanel);
//calling showNextRecord() method
showNextRecord();
resultPanel = new JPanel();
resultPanel.setLayout(new GridLayout(3,2));
resultPanel.setBounds(frameWidth/3,410,250,80);
totalQuestion = new JLabel("");
correct = new JLabel("");
attemptedQuestion = new JLabel("");
incorrect = new JLabel("");
unattemptedQuestion = new JLabel("");
resultPanel.add(totalQuestion);
resultPanel.add(correct);
resultPanel.add(attemptedQuestion);
resultPanel.add(incorrect);
resultPanel.add(unattemptedQuestion);
add(resultPanel);
resultPanel.hide();
restart = new JButton("Restart");
restart.setBounds(frameWidth/3,495,200,40);
restart.addActionListener(this);
add(restart);
restart.hide();
}catch(Exception ex){
System.out.println(ex.getMessage());
}
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
// show nextRecord() method
public void showNextRecord(){
if(count < 1){
previousButton.setEnabled(false);
}else{
previousButton.setEnabled(true);
}
if(count+1 == nor){
nextButton.setText("FINISH");
}else{
nextButton.setEnabled(true);
nextButton.setText("Next");
}
try{
//move the cursor to the specified row number
questionRst.absolute(count+1);
questionLabel.setText((count+1)+". "+questionRst.getString(2));
String split = questionRst.getString(3);
optionString = split.split("-");
optionsButton = new JRadioButton[optionString.length];
for(int i=0; i<optionString.length; i++){
optionsButton[i] = new JRadioButton(optionString[i]);
optionsButton[i].addItemListener(this);
buttonGroup.add(optionsButton[i]);
optionPanel.add(optionsButton[i]);
if(map.containsKey((questionRst.getLong(1)))){
if(map.get(questionRst.getLong(1)).equals(optionsButton[i].
getText()))
optionsButton[i].setSelected(true);
}else
buttonGroup.clearSelection();
}
add(optionPanel);
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
//childFrame() method which creates child frame
public void childFrame(){
try{
//creating another Frame to show complete result
childFrame = new JFrame();
childFrame.setSize(frameWidth,frameHight);
childFrame.setLayout(null);
title = new JLabel("Objective Test");
title.setBounds(frameHight/2,20,200,30);
title.setFont(new Font("Arial", Font.BOLD,20));
childFrame.add(title);
questionPanel = new JPanel();
questionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
questionPanel.setBounds(frameWidth/9,90,550,50);
questionLabel = new JLabel("");
questionPanel.add(questionLabel);
childFrame.add(questionPanel);
optionPanel = new JPanel();
optionPanel.setLayout(new GridLayout(4,2));
optionPanel.setBounds(frameWidth/9,150,550,150);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,2,5,5));
buttonPanel.setBounds(frameWidth/9,320,550,50);
childPreviousButton = new JButton("Previous");
childPreviousButton.addActionListener(this);
buttonPanel.add(childPreviousButton);
childNextButton = new JButton("Next");
childNextButton.addActionListener(this);
buttonPanel.add(childNextButton);
childFrame.add(buttonPanel);
childRestart = new JButton("Restart");
childRestart.setBounds(frameWidth/3,410,250,40);
childRestart.addActionListener(this);
childFrame.add(childRestart);
//calling childShowNextRecord()method
childShowNextRecord();
childFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
childFrame.setVisible(true);
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
// defining childShowNextRecord() method
public void childShowNextRecord(){
if(childCount<1) childPreviousButton.setEnabled(false);
else childPreviousButton.setEnabled(true);
if(childCount+1 == nor) childNextButton.setEnabled(false);
else childNextButton.setEnabled(true);
// creating border where no options are selected Border titleBorder = BorderFactory.createLineBorder(Color.RED);
TitledBorder title = BorderFactory.createTitledBorder(titleBorder,
"Not-Attempted");
title.setTitleJustification(TitledBorder.CENTER);
try{
questionRst.absolute(childCount+1);
questionLabel.setText((childCount+1)+". "+questionRst.getString(2));
String string = questionRst.getString(3); String[] optionString = string.split("-");
correctOption = questionRst.getString(4);
optionsButton = new JRadioButton[optionString.length];
for(int i=0; i<optionString.length; i++){
optionsButton[i] = new RadioButton(optionString[i]);
buttonGroup.add(optionsButton[i]);
optionPanel.add(optionsButton[i]);
if(map.containsKey((questionRst.getLong(1)))){
optionPanel.setBorder(null);
if(map.get(questionRst.getLong(1)).equals(optionsButton[i].
getText())){
optionsButton[i].setSelected(true);
icon = new ImageIcon("");
optionsButton[i].setIcon(icon);
optionsButton[i].setFont(new Font("Arial",Font.BOLD,18));
if(!map.get(questionRst.getLong(1)).equals(correctOption)){
icon1 = new ImageIcon("C:/Users/MSclient008/Desktop/
TarunDoc/icons/wrong.gif");
optionsButton[i].setIcon(icon1);
}
}
}else{
buttonGroup.clearSelection();
optionPanel.setBorder(title);
}
}
int k=0;
while(k<optionString.length){
if(correctOption.equals(optionsButton[k].getText())){
optionsButton[k].setFont(new Font("Arial",Font.BOLD,18));
icon3 = new ImageIcon("C:/Users/MSclient008/Desktop/
TarunDoc/icons/correct.gif");
optionsButton[k].setIcon(icon3);
}
k++;
}
childFrame.add(optionPanel);
Component[] component = optionPanel.getComponents(); int i=0,j=0;
while(component.length>i){
JRadioButton radio = (JRadioButton)component[i];
if(!radio.isSelected()){
radio.setEnabled(false);
j++;
}
if(radio.getText().equals(correctOption))
radio.setEnabled(true);
i++;
}
int x=0;
if(j==i)
{
while(component.length>x){
JRadioButton radio = (JRadioButton)component[x];
if(radio.getText().equals(correctOption)){
radio.setEnabled(false);
}
x++;
}
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
// defining actionPerformed() method
public void actionPerformed(ActionEvent ae){
JButton button = (JButton)ae.getSource(); try{ if(ae.getSource()==previousButton)
{
if(count>0)
{
count--;
optionPanel.removeAll();
optionPanel.repaint();
showNextRecord();
}
System.out.println("Prev:"+count);
}
if(ae.getSource()==nextButton)
{
if(count< nor-1)
{
optionPanel.removeAll();
optionPanel.repaint();
count++;
showNextRecord(); } else if(button.getText().equals("FINISH"))
{
Object[] options = {"Yes, please","Return!"};
// asking confirmation to show result
int n = JOptionPane.showOptionDialog(this, "Are you sure,
want to see result!","Test Result",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if(n ==0){
previousButton.setEnabled(false);
nextButton.setEnabled(false);
questionLabel.setEnabled(false);
resultButton.setEnabled(false);
showResult();
describeResultButton.setEnabled(true);
}
}
System.out.println("Next:"+count);
}
if(ae.getSource()==resultButton){
// calling showResult() method
showResult();
restart.show();
System.out.println("ResultButton:");
}
if(ae.getSource()==describeResultButton)
{
this.hide();
// calling childFrame() method
childFrame();
System.out.println("DescribeButton:");
}
if(ae.getSource()==childPreviousButton)
{
if(childCount>0)
{
childCount--;
optionPanel.removeAll();
optionPanel.repaint();
childShowNextRecord();
System.out.println("ChildPrev:"+childCount);
}
}
if(ae.getSource()==childNextButton)
{
if(childCount < nor-1)
{
optionPanel.removeAll();
optionPanel.repaint();
childCount++;
childShowNextRecord();
System.out.println("ChildNext:"+childCount);
}
}
if(ae.getSource()==restart)
{
this.hide();
new DynamicTest();
}
if(ae.getSource()==childRestart)
{
childFrame.hide();
new DynamicTest();
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
}
private void showResult(){
try{
int size=1, totalQ=0, attemptedQ=0,cor=0,inc=0; while(size <= nor){
String[] optionString = null;
String correctOption = null;
questionRst.absolute(size);
if(map.containsKey(questionRst.getLong(1))){
String split = questionRst.getString(3);
optionString = split.split("-");
questionRst.absolute(size);
correctOption = questionRst.getString(4);
if(map.get(questionRst.getLong(1)).equals(correctOption))
cor++;
else
inc++;
}
size++;
}
totalQuestion.setText("TotalQuestions"+" : "+(totalQ=nor));
attemptedQuestion.setText("Attempted"+":"+(attemptedQ=map.size()));
unattemptedQuestion.setText("Unattempted"+":"+(totalQ-attemptedQ));
correct.setText("Correct"+" : "+cor);
incorrect.setText("Incorrect"+" : "+inc);
resultPanel.show();
previousButton.setEnabled(false);
nextButton.setEnabled(false);
questionLabel.setEnabled(false);
Component[] component = optionPanel.getComponents();
int i=0;
while(component.length>i){
JRadioButton radio = (JRadioButton)component[i];
if(!radio.isSelected())
radio.setEnabled(false);
i++;
}
}catch(Exception e){
System.out.print(e.getMessage());
}
}
// defining connect() method to connect with the database
public void connect(){
try{
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection("jdbc:mysql://localhost:3306/test",
"root","1234");
statement = con.createStatement();
System.out.println("Connected");
}catch(Exception e){
System.out.print(e.getMessage());
}
}
public void itemStateChanged(ItemEvent e){ try{
JRadioButton radioButton = (JRadioButton)e.getSource();
if(radioButton.isSelected())
{
map.put(questionRst.getLong(1), radioButton.getText()); System.out.println("MapSize:"+map.size());
}
System.out.println("CheckedOption:"+map.get(questionRst.getLong(1)));
}catch(Exception ex){
System.out.print(ex.getMessage());
}
}
//defining main()method
public static void main(String ...s){
new DynamicTest();
}
}
Running the Application

Next, we will learn about : JAVA : Singleton Pattern
Leave a Comment