faqts : Computers : Programming : Languages : Java

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

41 of 52 people (79%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

How can I create a GUI quiz program to help me memorize information for a test using Java and Swing?

Jul 16th, 2002 08:49
Jason Stracner, http://www.innovation.ch/java/java_compile.htm


I have discovered that you can compile Java programs now with out even 
having a Java compiler installed on your computer.  There is a free 
online service that I have been using called JXXX Compiler Service 
that is available at:
http://www.innovation.ch/java/java_compile.htm  
It seems that all you have to do is create your Java code files and 
upload them to the service and it lets you download the resulting 
class files.  If there happens to be errors in your code it will 
instead show you the errors from the compiler.  At the time of this 
writing there are three versions of the JDK compiler available for 
your use these are: 1.0.2, 1.1.7 and 1.2.2.
To demonstrate some core Java concepts I will walk you through setting 
up this program.
Steps:
1. Create the source code file.
I have thrown together a simple Java program for this task.  For your 
use you can just copy this code into a file called Tester.java.
/*
 * Swing_Tester.java
 *
 * Created on June 12, 2002, 5:33 PM
 */
/**
 *
 * @author  JasonStracner
 */
import java.io.*;
import java.util.*;
import java.util.ListIterator;
import java.awt.event.*;
import javax.swing.*;
public class Swing_Tester extends javax.swing.JFrame {
    ArrayList questions = new ArrayList();
    ArrayList answers = new ArrayList();
    ArrayList explainations = new ArrayList();
    int iTotalQuestionsAnswered=0;
    int iTotalQuestionsAnsweredCorrectly=0;
    int iCurrentQuestion;
    boolean fQuestionWasAnswered;
    /** Creates new form Swing_Tester */
    public Swing_Tester() {
        initComponents();
    }
    String replace(String sOriginal, 
          String sSearchFor, 
          String sReplacement) {
      if (sOriginal.equals("")) return "";
      String sNewString = "";
      int iPosOfStr = sOriginal.indexOf(sSearchFor,0);
      int iLastPos = 0;
      while (iPosOfStr != -1) {
        sNewString += sOriginal.substring(
            iLastPos,iPosOfStr) + 
            sReplacement;
        iLastPos = iPosOfStr + sSearchFor.length();
        iPosOfStr = sOriginal.indexOf(sSearchFor,iLastPos);
      }
      sNewString += sOriginal.substring(iLastPos);
      return sNewString;  
    }
    private void setNewQuestion() {
        txtQuestion.setText("");
        iCurrentQuestion=(int)(Math.random()*questions.size());        
        txtQuestion.setText(txtQuestion.getText() 
          + "\nQuestion:\n");
        txtQuestion.setText(txtQuestion.getText() 
          + (String)questions.get(iCurrentQuestion));
        txtQuestion.setText(txtQuestion.getText() + "\n");
    }
    private void printScore() {
        float rScore = (float)iTotalQuestionsAnsweredCorrectly / 
            (float)iTotalQuestionsAnswered * 100F;
        rScore = java.lang.Math.round(rScore*10F)/10F;
        txtQuestion.setText(txtQuestion.getText() 
            + "\nYour score is: " + rScore + "%");
        txtQuestion.setText(txtQuestion.getText() + "\n" 
            + iTotalQuestionsAnsweredCorrectly 
            + " out of " + iTotalQuestionsAnswered);
    }
    private void showExplaination(){
        txtQuestion.setText(txtQuestion.getText() 
            + "Explaination:\n"
            + (String)explainations.get(iCurrentQuestion));
    }
    private void checkAnswer() {
        txtQuestion.setText(txtQuestion.getText() 
            + "\n" + txtAnswer.getText());
        if (txtAnswer.getText().equals(
            (String)answers.get(iCurrentQuestion))) {
          txtQuestion.setText(txtQuestion.getText() 
            + "\n     Right!\n");
          iTotalQuestionsAnswered++;
          iTotalQuestionsAnsweredCorrectly++;
        } else {
          txtQuestion.setText(txtQuestion.getText() 
            + "\nWrong.");
          txtQuestion.setText(txtQuestion.getText() 
            + "\nThe correct answer is: '"
            + (String)answers.get(iCurrentQuestion)
            + "' not '" + txtAnswer.getText() + "'\n");
          iTotalQuestionsAnswered++;
        }
    }
    //
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {
        jScrollPane4 = new javax.swing.JScrollPane();
        txtQuestion = new javax.swing.JTextArea();
        txtAnswer = new javax.swing.JTextField();
        setFont(new java.awt.Font("Arial", 0, 10));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                exitForm(evt);
            }
        });
        txtQuestion.setEditable(false);
        txtQuestion.setLineWrap(true);
        txtQuestion.setWrapStyleWord(true);
        jScrollPane4.setViewportView(txtQuestion);
        getContentPane().add(jScrollPane4, 
                 java.awt.BorderLayout.CENTER);
        txtAnswer.setText("Type your answer here and press enter.  
Press enter a second time to move to the next question.");
        txtAnswer.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtAnswerKeyPressed(evt);
            }
        });
        getContentPane().add(txtAnswer, java.awt.BorderLayout.SOUTH);
        pack();
        java.awt.Dimension screenSize = 
              java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setSize(new java.awt.Dimension(600, 300));
        setLocation((screenSize.width-600)/2,
              (screenSize.height-300)/2);
    }
    private void txtAnswerKeyPressed(java.awt.event.KeyEvent evt) {
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            if (fQuestionWasAnswered) {
                txtAnswer.setText("");
                setNewQuestion();
            } else {
                checkAnswer();
                showExplaination();
                printScore();
            }
            fQuestionWasAnswered = !fQuestionWasAnswered;
        }
    }
    private void formWindowOpened(java.awt.event.WindowEvent evt) {
        // Add your handling code here:
        BufferedReader oBufferedReader;
        String sLineOfText;
        try {
          oBufferedReader = new BufferedReader(
              new FileReader("fill_in_the_blanks.txt"));
          String sSection = "q";
          String sLineToAdd = "";
          while((sLineOfText = oBufferedReader.readLine())!= null) {
            if (sLineOfText.indexOf("<q>")>=0) {
                sSection = "q";
                sLineOfText = replace(sLineOfText, "<q>","");
            } else if (sLineOfText.indexOf("<a>")>=0) {
                sSection = "a";
                sLineOfText = replace(sLineOfText, "<a>","");
            } else if (sLineOfText.indexOf("<e>")>=0) {
                sSection = "e";
                sLineOfText = replace(sLineOfText, "<e>","");
            }
            if (sLineOfText.indexOf("</q>")>=0) {
                sSection = "/q";
                sLineOfText = replace(sLineOfText, "</q>","");
            } else if (sLineOfText.indexOf("</a>")>=0) {
                sSection = "/a";
                sLineOfText = replace(sLineOfText, "</a>","");
            } else if (sLineOfText.indexOf("</e>")>=0) {
                sSection = "/e";
                sLineOfText = replace(sLineOfText, "</e>","");
            } 
            if (sLineToAdd.equals("")) {
                sLineToAdd = sLineOfText;
            } else {
                sLineToAdd = sLineToAdd + "\n" + sLineOfText;
            }
            if (sSection.equals("/q")) {
              questions.add(sLineToAdd);
              sLineToAdd = "";
              sSection = "";
            } else if (sSection.equals("/a")) {
              answers.add(sLineToAdd);
              sLineToAdd = "";
              sSection = "";
            } else if (sSection.equals("/e")) {
              explainations.add(sLineToAdd);
              sLineToAdd = "";
              sSection = "";
            }
          }
          oBufferedReader.close();
        } catch (IOException ioe) {
          JOptionPane.showMessageDialog(this, 
              "Couldn't open the file fill_in_the_blanks.txt.",
              "Question file error:", JOptionPane.INFORMATION_MESSAGE);
          System.exit(0);
        };
        txtAnswer.requestFocus();
        txtAnswer.setSelectionStart(0);
        txtAnswer.setSelectionEnd(txtAnswer.getText().length());
        //Show the first question.
        setNewQuestion();
    }
    /** Exit the Application */
    private void exitForm(java.awt.event.WindowEvent evt) {
        System.exit(0);
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        new Swing_Tester().show();
    }
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTextArea txtQuestion;
    private javax.swing.JTextField txtAnswer;
    // End of variables declaration
}
//End of code----------------
2. Next go to the JXXX Compiler Service’s web page and choose the file 
   you created in step one and be sure to select the JDK version 1.2.2
   so that you will have access to the new Java 2 Swing GUI libraries. 
   Then click ‘Compile’.
3. Wait.
4. When the browser displays the compiled class files select the file 
   that is a zip file.  This file will contain all the class files 
   that are needed to run your application.  Download and unzip these 
   files into an empty folder.
5. One of the best ways to run Java applications is to turn them into 
   executable JAR files.  In windows you can simply double-click on an 
   executable JAR file and it will run just like an .exe file.  Here is
   how you can use the zip file we just made to turn it into an 
   executable JAR file.
  a. Within the folder you unzipped the compiled class files into in 
     step four create a subfolder called “meta-inf”.  Create a file in 
     this subfolder called “Manifest.mf”.
  b. Inside this new file put a single line of text:
Main-Class: Tester
     Make sure that you press the Enter key at the end of the single 
     line of text.  I have heard of people having problems by not 
     having that extra character that is made by the Enter key at the 
     end of the manifest.mf file.
  c. Use WinZip or some other zip utility to zip the class files and 
     the “meta-inf” folder into a zip file.  The structure within the 
     zip file should be like this:
       Tester.class
       Tester$1.class
       Tester$2.class
       meta-inf\ Manifest.mf
  d. Rename the zip file to “Tester.jar”.
  e. Now as long as you have a copy of the JRE or JDK of 1.3 or 
     greater you can just double-click on the jar file to run the 
     program.
  f. You will also need the ‘questions and answers’ file in order for 
     this program to be of much use.  All you have to do to get the 
     thing to display you questions is to create a file that is in the 
     same folder as your JAR file called “fill_in_the_blanks.txt”.  In 
     this file the program identifies the text between the <q> and
     the </q> tags as a question, the text between the <a> and the
     </a> as the answer and the text between the <e> and </e> tags
     as the explaination for the answer.  All three sections must
     be present for each question.  Remember that the text that you
     give for the answer shouldn't contain a new line character 
     (The enter key) because you can only type a single line for the
     answer.
I hope this helps someone out on a test or maybe helps programmers 
understand some of the basic concepts of doing Java programming.  If 
you have any comments on this article please email me at:
  article_comments@lr-tc.com.