检查反应时间

时间:2016-02-16 06:13:06

标签: java swing timer actionlistener

在我的程序中,这是用于检查反应时间的试验认知程序,以下代码在Netbeans IDE中编写,在此代码中,出现了两个主要问题:

  1. 单击下一个按钮时,数组索引值跳跃。问题发生在前两个问题之后。

  2. 内定时器循环不能正常工作,当数组索引Qno 2跳转Qno 4,然后内定时器循环启动两次,我明白,一个定时器用于Qno 3,另一个定时器用于Qno4。

  3. 代码是:

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.text.NumberFormat;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JDesktopPane;
    import javax.swing.JLabel;
    import javax.swing.JRadioButton;
    import javax.swing.Timer;
    
    /**
     *
     * @author Rajesh K, Tech. Asst. B
     */
    public final class DigitCalc extends javax.swing.JFrame {
    
        /**
         * Creates new form DigitCalc
         */
    
        /* TIMER VARIABLES*/
        long completeTestRemaining = 0; // How many milliseconds remain in the countdown.
        long completeTestLastUpdate = 0; // When count was last updated
        NumberFormat format; // Format minutes:seconds with leading zeros
        Timer completeTestTimer;
        int completeTestminutes = 0;
        int completeTestseconds = 0;
        long now; // current time in ms
        long elapsed; // ms elapsed since last update
        String min = "00",
                sec = "00";
        int iDelayTimer, totalTime;
        //END OF COMPLETE TEST TIMER
    
        //START QUESITON TIMER
        long qRemaining = 0; // How many milliseconds remain in the countdown.
        long qLastUpdate = 0; // When count was last updated
        Timer qTimer;
        int qMinutes = 0;
        int qSeconds = 0;
        long qNow = 0;
        long qElapsed = 0;
        int qDelayTimer;
    
        //END OF QUESTION TIMER
        Insets insets, frmInsets;
        Dimension size;
        Dimension screenSize;
        double width, height;
        JDesktopPane desktopPane;
        String bCode, bRN, bName, bDOT;
        JButton nextBtn = new JButton();    //goto for next item
        ButtonGroup radioGroup;   //using for at a time one radio selection
        private JRadioButton radioT;
        private JRadioButton radioF;
        JLabel lblQNO, lblQuestion, lblOption, lblT, lblF, lblTimer;
        int i, row = 0;
        int totQCounter;
        Font font;
    
        //get the user respone
        String str = null;  //get the user response from radio key
        int totalScore = 0;   //when all raw score  calculated
        int[] score;  //get the raw score
        int wscore; //get the wrong score, if score is not correct
        int totalQ = 0; //get the total question from qno list of array 
        String[] userResp;  //take user response
    
        //Question Array
        String[] qArray = {
            "5 + 6 - 8 = ",
            "2 + 3 - 3 = ",
            "8 - 4 + 7 = ",
            "7 + 9 - 6 = ",
            "6 - 1 - 1 = ",
            "4 + 9 - 7 = "
        };
    
        //Option Array for each question
        String[] oArray = {"3", "4", "3", "10", "4", "6"};
    
        //Answer key
        String[] ansKey = {"T", "F", "T", "T", "T", "T"};
    
        public DigitCalc() {
            //GET THE DEFAULT SCREEN SIZE
            screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            width = screenSize.getWidth();
            height = screenSize.getHeight();
            initComponents();
            this.setSize(screenSize);
            this.setResizable(false);
            insets = testPanel.getInsets();
            font = new Font("Arial", Font.BOLD, 18);
            frmInsets = getInsets();
            //lblName.setText("RR");
            //GET THE OVERALL TEST TIMER i.e. 5min
            getTestTimer();
    
            //for(i=0;i<qArray.length;i++)
            //  System.out.println("Qno: "+i+" question is "+qArray[i]+" and option is: "+oArray[i]+" = "+ansKey[i]);
            totalQ = 6;
            totQCounter = 0;
            userResp = new String[totalQ];
            score = new int[totalQ];
            for (i = 0; i < totalQ; i++) {
                userResp[i] = "";
                score[i] = 0;
            }
    
            widgetDeclaration();
            addComponentsQ();
            //START INNER TIMER FOR QUESTION FOR Q1
            getQTimer();
        }
    
        public void getTestTimer() {
            //SET THE OVERALL TEST TIMER VARIABLES
            completeTestRemaining = 5 * 60 * 1000; //03min 
            format = NumberFormat.getNumberInstance();
            format.setMinimumIntegerDigits(2); // pad with 0 if necessary
            iDelayTimer = 1000;
            completeTestTimer = new Timer(iDelayTimer, totalTesttimerEventTest);
            completeTestTimer.setInitialDelay(0);
            completeTestLastUpdate = System.currentTimeMillis();
            completeTestTimer.start(); // Start the timer
    
            //set the label timer for complete test
            lblTimer = new JLabel();
            lblTimer.setBackground(new java.awt.Color(255, 255, 255));
            lblTimer.setFont(new java.awt.Font("Tahoma", 1, 20)); // NOI18N
            lblTimer.setForeground(Color.BLUE);
            lblTimer.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            lblTimer.setOpaque(true);
            size = lblTimer.getPreferredSize();
            lblTimer.setBounds((int) (width - 100), 10, 70, 20);
            testPanel.add(lblTimer);
            lblTimer.setText(format.format(completeTestminutes) + ":" + format.format(completeTestseconds));
            lblTimer.repaint();
            //END OF TIMER SETTING                
        }
    
        public void widgetDeclaration() {
            nextBtn = new JButton();
            lblQNO = new JLabel();
            lblQuestion = new JLabel();
            lblOption = new JLabel();
            radioT = new JRadioButton();
            radioF = new JRadioButton();
            radioGroup = new ButtonGroup();
            lblT = new JLabel();
            lblF = new JLabel();
            str = "";
        }
    
        public void addComponentsQ() {
            //SHOW QUESTION NUMBER
            lblQNO.setBackground(new java.awt.Color(255, 255, 255));
            lblQNO.setFont(new java.awt.Font("Tahoma", 1, 40)); // NOI18N
            lblQNO.setForeground(Color.BLUE);
            lblQNO.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            lblQNO.setText("QNo. " + (int) (totQCounter + 1));
            lblQNO.setOpaque(true);
            size = lblQNO.getPreferredSize();
            lblQNO.setBounds(50 + insets.left, 50 + insets.top, size.width + 40, size.height + 60);
            testPanel.add(lblQNO);
    
            lblQuestion.setBackground(new java.awt.Color(255, 255, 255));
            lblQuestion.setFont(new java.awt.Font("Tahoma", 1, 40)); // NOI18N
            lblQuestion.setForeground(Color.BLUE);
            lblQuestion.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            lblQuestion.setText("" + qArray[totQCounter]);    //set the random question values
            lblQuestion.setOpaque(true);
            size = lblQuestion.getPreferredSize();
            lblQuestion.setBounds(450 + insets.left, 300 + insets.top, size.width + 30, size.height + 50);
            testPanel.add(lblQuestion);
        }
    
        //FOR OPTION AFTER SHOWING THE QUESTION
        public void addComponentsO() {
            lblOption.setBackground(new java.awt.Color(255, 255, 255));
            lblOption.setFont(new java.awt.Font("Tahoma", 1, 40)); // NOI18N
            lblOption.setForeground(Color.BLUE);
            lblOption.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            lblOption.setText("" + oArray[totQCounter]);    //set the random question values
            lblOption.setOpaque(true);
            size = lblOption.getPreferredSize();
            lblOption.setBounds(440 + insets.left, 250 + insets.top, size.width + 30, size.height + 50);
            testPanel.add(lblOption);
    
            radioT.setBounds(380 + insets.left, 380 + insets.top, 40, 30);
            radioT.setFont(new java.awt.Font("Tahoma", 1, 25)); // NOI18N
            radioT.setText("T");
            radioT.setBackground(new java.awt.Color(255, 255, 255));
            radioGroup.add(radioT);
            radioT.setActionCommand("T");
            testPanel.add(radioT);
    
            radioF.setBounds(550 + insets.left, 380 + insets.top, 40, 30);
            radioF.setFont(new java.awt.Font("Tahoma", 1, 25));
            radioF.setText("F");
            radioF.setBackground(new java.awt.Color(255, 255, 255));
            radioGroup.add(radioF);
            radioF.setActionCommand("F");
            testPanel.add(radioF);
        }
    
        private void clearSelection() {
            radioGroup.clearSelection();
        }
    
        //CLEAR THE OPTION AND NEXT BUTTON WHEN NEXT BUTTON CLICKED
        private void clearOption() {
            testPanel.remove(lblOption);
            testPanel.remove(radioT);
            testPanel.remove(radioF);
            testPanel.remove(nextBtn);
        }
    
        //CLEAR THE QUESTION SET WHEN INNER TIMER HAVE COMPLETED I.E. 5 SECONDS
        private void clearQuestion() {
            testPanel.remove(lblQNO);
            testPanel.remove(lblQuestion);
        }
    
        //GET THE TIMER FOR EACH QUESTION
        public void getQTimer() {
            qLastUpdate = qNow = qElapsed = qRemaining = qMinutes = qSeconds = 0;
            qRemaining = (long) (1 * 60 * 1000) / 12; // QUESTION SHOWS IN 5 sec ON THE DISPLAY
            qDelayTimer = 1000;
            qTimer = new Timer(qDelayTimer, qTimerEventTest);
            qTimer.setInitialDelay(0);
            qLastUpdate = System.currentTimeMillis();
            qTimer.start(); // Start the timer
        }
    
        //GET THE BUTTON INFO.
        public void getNextButtonInfo() {
            nextBtn.setText("Next");
            nextBtn.setToolTipText("Next Item");
            nextBtn.setMnemonic(KeyEvent.VK_N);
            nextBtn.setFont(new java.awt.Font("Tahoma", 1, 18));
            size = nextBtn.getPreferredSize();
            nextBtn.setBounds((int) (950) + insets.left, (int) (height - 100) + insets.top, size.width + 30, size.height + 10);
            nextBtn.addActionListener(btnListen);
            testPanel.add(nextBtn);
        }
    
        //BUTTON LISTENER
        ActionListener btnListen = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getActionCommand() == "Next") {
                    if (radioGroup.getSelection() != null) {
                        String stResp = radioGroup.getSelection().getActionCommand();
                        userResp[totQCounter] = stResp;
                        //System.out.println("User Resp: "+userResp[totQCounter]+" from  question number is "+totQCounter);
                    } else {
                        userResp[totQCounter] = "X";
                    }
    
                    if (totQCounter < (totalQ - 1)) {
                        totQCounter++;
                        clearSelection();
                        clearOption();
                        testPanel.repaint();
                        addComponentsQ();
                        getQTimer();
                    } else {
                        nextBtn.setText("Submit");
                    }
                }//end of next button click
                else if (e.getActionCommand() == "Submit") {
                    completeTestTimer.stop();
                    if (radioGroup.getSelection() != null) {
                        String stResp = radioGroup.getSelection().getActionCommand();
                        userResp[totQCounter] = stResp;
                        //System.out.println("User Resp: "+userResp[totQCounter]+" for question number is "+totQCounter);
                    } else {
                        userResp[totQCounter] = "X";
                    }
    
                    //                for(i=0;i<ansKey.length;i++)
                    //                    System.out.println("ANO: "+i+"Answer "+ansKey[i]);
                    for (i = 0; i < userResp.length; i++) {
                        //System.out.println(userResp[i]);
                        if (ansKey[i].equals(userResp[i])) {
                            score[i] = 1;
                        } else {
                            score[i] = 0;
                        }
                    }
                    for (i = 0; i < userResp.length; i++) {
                        System.out.println(score[i]);
                    }
                    System.exit(0);
                }
            }
        };
    
        //QUESTION TIMER LISTENER
        ActionListener qTimerEventTest = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                qNow = System.currentTimeMillis(); // current qtime in ms
                qElapsed = qNow - qLastUpdate; // ms elapsed since last update
                qRemaining -= qElapsed; // adjust remaining time 
                qLastUpdate = qNow; // remember this update time
                qMinutes = (int) (qRemaining / 60000);
                qSeconds = (int) ((qRemaining % 60000) / 1000);
    
                if (qRemaining < 0) {
                    qRemaining = 0;
                }
    
                                //System.out.println("From question timer class: "+totQCounter+" and question is "+qArray[totQCounter]);
                //System.out.println("From question timer class: "+totQCounter);
                System.out.println("Remaining Timer of  Question " + totQCounter + "  is: " + qRemaining);
                // If we've completed the countdown beep and display new page
                if (qRemaining == 0) {
                    qTimer.stop();
                    //System.out.println("Qno: "+(totQCounter)+"  option is: "+oArray[totQCounter]);
                    clearQuestion();
                    testPanel.repaint();
                    addComponentsO();
                    getNextButtonInfo();
                }
            }
        };
    
        /*using of remaining time for OVERALL TEST  */
        ActionListener totalTesttimerEventTest = new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                now = System.currentTimeMillis(); // current time in ms
                elapsed = now - completeTestLastUpdate; // ms elapsed since last update
                completeTestRemaining -= elapsed; // adjust remaining time
                completeTestLastUpdate = now; // remember this update time
                completeTestminutes = (int) (completeTestRemaining / 60000);
                completeTestseconds = (int) ((completeTestRemaining % 60000) / 1000);
    
                if (completeTestRemaining < 0) {
                    completeTestRemaining = 0;
                }
    
                               // System.out.println("From Complete Timer Class: "+totQCounter);
                // If we've completed the countdown beep and display new page
                //System.out.println("Complete Test Time is "+completeTestRemaining);
                if (completeTestRemaining == 0) {
                    completeTestTimer.stop();
                    nextBtn.setText("Submit");
                } else {
                    lblTimer.setText(format.format(completeTestminutes) + ":" + format.format(completeTestseconds));
                    lblTimer.repaint();
                }
            }//end of action performed function
        };
    
        @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            testPanel = new javax.swing.JPanel();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    
            testPanel.setBackground(new java.awt.Color(255, 255, 255));
    
            javax.swing.GroupLayout testPanelLayout = new javax.swing.GroupLayout(testPanel);
            testPanel.setLayout(testPanelLayout);
            testPanelLayout.setHorizontalGroup(
                    testPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGap(0, 561, Short.MAX_VALUE)
            );
            testPanelLayout.setVerticalGroup(
                    testPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGap(0, 381, Short.MAX_VALUE)
            );
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(testPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addContainerGap())
            );
            layout.setVerticalGroup(
                    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addContainerGap()
                            .addComponent(testPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addContainerGap())
            );
    
            pack();
        }// </editor-fold>   
    
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(DigitCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(DigitCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(DigitCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(DigitCalc.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new DigitCalc().setVisible(true);
                }
            });
        }
        private javax.swing.JPanel testPanel;
    }
    

1 个答案:

答案 0 :(得分:0)

我解决了我的问题问题,只是使用了布尔值并检查了条件,这是真的与否,以下代码运行正确,

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JDesktopPane;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.Timer;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author my
 */
public class digitCalculation extends javax.swing.JFrame {


     /* TIMER VARIABLES*/
    long completeTestRemaining = 0; // How many milliseconds remain in the countdown.
    long completeTestLastUpdate = 0; // When count was last updated
    NumberFormat format; // Format minutes:seconds with leading zeros
    Timer completeTestTimer;
    int completeTestminutes=0 ;
    int completeTestseconds=0 ;
    long now ; // current time in ms
    long elapsed ; // ms elapsed since last update
    String min="00",
                sec="00";
    int   iDelayTimer,totalTime;
    //END OF COMPLETE TEST TIMER



    //START QUESITON TIMER
    long qRemaining = 0; // How many milliseconds remain in the countdown.
    long qLastUpdate = 0; // When count was last updated
   Timer qTimer;
    int qMinutes=0 ;
    int qSeconds=0 ;
    long qNow = 0;
    long qElapsed=0;
    int qDelayTimer;

    //FOR USER RESPONSE DELAY TIME
    long getingResponseTime = 0;
    //END OF QUESTION TIMER    

    Insets insets,frmInsets;
    Dimension size;
    boolean bNext;

    Dimension screenSize;
    double width, height;
    JDesktopPane desktopPane;        
    String bCode, bRN, bName, bDOT;


    int totalScore=0;   //when all raw score  calculated
    int []score;  //get the raw score
    int wscore; //get the wrong score, if score is not correct
    int totalQ = 0; //get the total question from qno list of array 
    String []userResp;  //take user response

    //Question Array
    String []qArray = {
                                        "5 + 6 - 8 = ",
                                        "2 + 3 - 3 = ",
                                        "8 - 4 + 7 = ",
                                        "7 + 9 - 6 = ",
                                        "6 - 1 - 1 = ",
                                        "4 + 9 - 7 = "
                                        };
    //Option Array for each question
    String []oArray = {
                                        "3", "4", "3", "10", "4","6"
                                    };

    //Answer key
    String []ansKey = { "T", "F", "T", "T", "T","T" };



    //String []qDigits = {"458","895","25689","8562","683","58798"};
    String stTemp = "";
    int totQCounter = 0;
    int i,row = 0;

    ButtonGroup radioGroup;   //using for at a time one radio selection
    private JRadioButton radioT;
    private JRadioButton radioF;
    JLabel lblQNO, lblQ, lblOption, lblT, lblF, lblTimer;
    JLabel lblAns;
    JButton  nextBtn;



    public digitCalculation() 
    {
        screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        width = screenSize.getWidth();
        height = screenSize.getHeight();
        qLastUpdate = qNow = qElapsed = qRemaining = qMinutes = qSeconds = 0;

        initComponents();
        this.setSize(screenSize);
        this.setResizable(false);
        insets = testPanel.getInsets();     

        lblQNO = new JLabel("");
        lblQ = new JLabel();
        nextBtn = new JButton();
        lblOption = new JLabel();
        radioT = new JRadioButton();
        radioF = new JRadioButton();
        radioGroup = new ButtonGroup();
        lblT = new JLabel();
        lblF = new JLabel();
        stTemp = "";

        bNext = false;
        totalQ = 6;
        totQCounter = 0;


        userResp = new String[totalQ];
        score  = new int[totalQ];
        for(i=0;i<totalQ;i++)
        {
            userResp[i] = "";
            score[i] = 0;
        }     

        nextBtn.setText("Next");
        nextBtn.setToolTipText("Next Item");
        nextBtn.setMnemonic(KeyEvent.VK_N);
        nextBtn.setFont(new java.awt.Font("Tahoma", 1, 18)); 
        size = nextBtn.getPreferredSize();
        nextBtn.setBounds((int)(950)+insets.left, (int)(height-100) + insets.top,size.width+30, size.height+10);


        addComponetsQ();
        getQTimerInterval();
        getTestTimer();
    }


     public void getTestTimer()
    {
        //SET THE OVERALL TEST TIMER VARIABLES
        completeTestRemaining = 5 * 60 * 1000; //03min 
        format = NumberFormat.getNumberInstance();
        format.setMinimumIntegerDigits(2); // pad with 0 if necessary
        iDelayTimer = 1000;
        completeTestTimer = new Timer(iDelayTimer, totalTesttimerEventTest);
        completeTestTimer.setInitialDelay(0);
        completeTestLastUpdate = System.currentTimeMillis();
        completeTestTimer.start(); // Start the timer

        //set the label timer for complete test
        lblTimer = new JLabel();
        lblTimer.setBackground(new java.awt.Color(255,255,255));
        lblTimer.setFont(new java.awt.Font("Tahoma", 1, 20)); // NOI18N
        lblTimer.setForeground(Color.BLUE);
        lblTimer.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTimer.setOpaque(true);
        size = lblTimer.getPreferredSize();
        lblTimer.setBounds((int) (width-100), 10, 70, 20);
        testPanel.add(lblTimer);
        lblTimer.setText(format.format(completeTestminutes) + ":" + format.format(completeTestseconds));
        lblTimer.repaint();
        //END OF TIMER SETTING                
    }


    private void getQTimerInterval()
    {
        qLastUpdate = qNow = qElapsed = qRemaining = qMinutes = qSeconds = 0;
        //qRemaining = (long) (1 * 60 * 1000)/12; // QUESTION SHOWS IN 5 sec ON THE DISPLAY        
        qRemaining = 5; //5 sec
        //System.out.println("qRemainingssss: "+qRemaining);
        qDelayTimer = 1000;
        qTimer = new Timer(qDelayTimer, QTimerEvent);
        qTimer.setInitialDelay(0);
        qLastUpdate = System.currentTimeMillis();
        qTimer.start(); // Start the timer
    }



    private void addComponetsQ()
    {
            //SHOW QUESTION NUMBER
            lblQNO.setVisible(true);
           lblQNO.setBackground(new java.awt.Color(255,255,255));
           lblQNO.setFont(new java.awt.Font("Tahoma", 1, 40)); // NOI18N
           lblQNO.setForeground(Color.BLUE);
           lblQNO.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
           lblQNO.setText("QNo. "+(int)(totQCounter+ 1));
           lblQNO.setOpaque(true);
           size = lblQNO.getPreferredSize();
           lblQNO.setBounds(50+insets.left,  50+insets.top,size.width+40, size.height+60);
           testPanel.add(lblQNO);

           lblQ.setVisible(true);
            lblQ.setBackground(new java.awt.Color(255,255,255));
            lblQ.setFont(new java.awt.Font("Tahoma", 1, 40)); // NOI18N
            lblQ.setForeground(Color.BLUE);
            lblQ.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            lblQ.setText(""+qArray[totQCounter]);    //set the random question values
            lblQ.setOpaque(true);
            size = lblQ.getPreferredSize();
            lblQ.setBounds(450 + insets.left,  300+insets.top,size.width+30, size.height+50);
            testPanel.add(lblQ);
    }


    private void clearSelection()
    {
        radioGroup.clearSelection();
    }

    //CLEAR THE OPTION AND NEXT BUTTON WHEN NEXT BUTTON CLICKED
    private void clearOption()
    {
        testPanel.remove(lblOption);
        testPanel.remove(radioT);
        testPanel.remove(radioF);
        testPanel.remove(nextBtn);
    }

    private void getButtonInfo()
    {
        testPanel.add(nextBtn);
        nextBtn.addActionListener(btnListen);   
        bNext = true;
    }

    private void clearQuestion()
    {
        testPanel.remove(lblQNO);
        testPanel.remove(lblQ);
    }


    //FOR OPTION AFTER SHOWING THE QUESTION
    public void addComponentsO()
    {
        lblOption.setBackground(new java.awt.Color(255,255,255));
        lblOption.setFont(new java.awt.Font("Tahoma", 1, 40)); // NOI18N
        lblOption.setForeground(Color.BLUE);
        lblOption.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblOption.setText(""+oArray[totQCounter]);    //set the random question values
        lblOption.setOpaque(true);
        size = lblOption.getPreferredSize();
        lblOption.setBounds(440+insets.left,  250+insets.top,size.width+30, size.height+50);
        testPanel.add(lblOption);


        radioT.setBounds(380 + insets.left, 380+insets.top,40, 30);
        radioT.setFont(new java.awt.Font("Tahoma", 1, 25)); // NOI18N
        radioT.setText("T");
        radioT.setBackground(new java.awt.Color(255,255,255));
        radioGroup.add(radioT);
        radioT.setActionCommand("T");
        testPanel.add(radioT);


        radioF.setBounds(550 + insets.left, 380 + insets.top, 40, 30);
        radioF.setFont(new java.awt.Font("Tahoma", 1, 25)); 
        radioF.setText("F");
        radioF.setBackground(new java.awt.Color(255,255,255));
        radioGroup.add(radioF);
        radioF.setActionCommand("F");
        testPanel.add(radioF);
    }

    ActionListener QTimerEvent = new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            qNow = System.currentTimeMillis(); // current qtime in ms
            qElapsed = qNow - qLastUpdate; // ms elapsed since last update
            //qRemaining -= qElapsed; // adjust remaining time 

            qLastUpdate = qNow; // remember this update time
            qMinutes = (int)(qRemaining/60000);
            qSeconds = (int)((qRemaining%60000)/1000);           
           // System.out.println("qRemaining: "+qRemaining);
            // System.err.println("zzzz: "+totQCounter);

            if (qRemaining   >  0) 
            {
                qRemaining--;  // adjust remaining time 
            }           
            else if (qRemaining <= 0) 
            {
                qTimer.stop();
                qTimer.removeActionListener(btnListen);
                System.err.println("frm timer: counter: "+totQCounter);
                clearQuestion();
                testPanel.validate();
                testPanel.repaint();

                addComponentsO();
                getButtonInfo();
            }
        }
    };

    ActionListener btnListen = new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            if(e.getActionCommand() == "Next")
            {
                if(radioGroup.getSelection() != null)
                {
                    String stResp = radioGroup.getSelection().getActionCommand();
                    userResp[totQCounter] = stResp;
                }
                else
                    userResp[totQCounter] = "X";


                if(totQCounter < (totalQ - 1 ))
                {
                    qTimer.stop();
                    qTimer.removeActionListener(QTimerEvent);
                    qLastUpdate = qNow = qElapsed = qRemaining = qMinutes = qSeconds = 0;
                    if(bNext )
                    {
                        //getingResponseTime
                        totQCounter++;
                        bNext = false;
                    }
                }
                else
                {
                    completeTestTimer.stop();
                    completeTestTimer.removeActionListener(totalTesttimerEventTest);
                    qTimer.stop();
                    qTimer.removeActionListener(QTimerEvent);
                    qLastUpdate = qNow = qElapsed = qRemaining = qMinutes = qSeconds = 0;
                    nextBtn.setText("Submit");
                }
            }
            else if(e.getActionCommand() == "Submit")
            {
                completeTestTimer.stop();
                if(radioGroup.getSelection() != null)
                {
                    String stResp = radioGroup.getSelection().getActionCommand();
                    userResp[totQCounter] = stResp;
                }   
                else
                    userResp[totQCounter] = "X";

                for(i=0;i<userResp.length;i++)
                {
                    if(ansKey[i].equals(userResp[i]))
                    {
                        score[i] = 1;
                    }
                    else
                        score[i] = 0;
                }
                for(i=0;i<userResp.length;i++)
                {
                    System.out.println(score[i]);
                }
                System.exit(0);
            }
            clearOption();
            clearSelection();
            testPanel.validate();
            testPanel.repaint();
            addComponetsQ();
            getQTimerInterval();

        }
    };

      /*using of remaining time for OVERALL TEST  */
    ActionListener totalTesttimerEventTest = new ActionListener()
    {
        public void actionPerformed(ActionEvent evt)
        {
           now = System.currentTimeMillis(); // current time in ms
           elapsed = now - completeTestLastUpdate; // ms elapsed since last update
           completeTestRemaining -= elapsed; // adjust remaining time
           completeTestLastUpdate = now; // remember this update time
           completeTestminutes = (int)(completeTestRemaining/60000);    //using for 
           completeTestseconds = (int)((completeTestRemaining%60000)/1000);           

            if (completeTestRemaining < 0) 
                completeTestRemaining = 0; 

           // System.out.println("From Complete Timer Class: "+totQCounter);
            // If we've completed the countdown beep and display new page
            //System.out.println("Complete Test Time is "+completeTestRemaining);
            if (completeTestRemaining == 0) 
            {
                completeTestTimer.stop();
                nextBtn.setText("Submit");
            }
            else
            {
               lblTimer.setText(format.format(completeTestminutes) + ":" + format.format(completeTestseconds));
               lblTimer.repaint();
            }
        }//end of action performed function
    };        


    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        testPanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        testPanel.setBackground(new java.awt.Color(255, 255, 255));
        testPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        javax.swing.GroupLayout testPanelLayout = new javax.swing.GroupLayout(testPanel);
        testPanel.setLayout(testPanelLayout);
        testPanelLayout.setHorizontalGroup(
            testPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 570, Short.MAX_VALUE)
        );
        testPanelLayout.setVerticalGroup(
            testPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 395, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(testPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(testPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(digitCalculation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(digitCalculation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(digitCalculation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(digitCalculation.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new digitCalculation().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel testPanel;
}

并且,以上代码运行良好;享受测试,您可以实施检查孩子(6-10岁年龄组)的反应时间。这基本上用于数字计算认知测试。他们如何解决计算难题?所以尽情享受!