Results 1 to 7 of 7

Thread: Problem in java

  1. #1
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default Problem in java

    I'm doing a quiz where a user can choose from 3 different quizzez. The questions are stored in a textfile. I wish that the questions are answered within a specified amount of time (i.e a count down timer). If the user isn't able to answer the answers within a specified amount of time, the quiz issues a message showing time is over, and then it should stop showing the questions and display the points scored. I managed to make a count down timer, but my problem is that after the message "time is over" is displayed it continues to display the questions, and so the user can continue answer them, and this is a bit ridiculous. Can someon pls help me figure out my mistake? Thanks a lot. :-)

    This are the classes of the quiz:

    1.ActionSupport:


    Java Code:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Calendar;
     
    import javax.swing.event.EventListenerList;
     
    public class ActionSupport {
     
    	protected EventListenerList listenerList = new EventListenerList();
    	private Object bean;
     
    	public ActionSupport(Object registeredBean) {
    		this.bean = registeredBean;
    	}
     
    	public void fireActionPerformed(String actionCommand) {
    		
    		Object[] listeners = listenerList.getListenerList();
    		ActionEvent e = null;
    		
    		for (int i = listeners.length - 2; i >= 0; i -= 2) {
    			if (listeners[i] == ActionListener.class) {
    				e = new ActionEvent(bean, ActionEvent.ACTION_PERFORMED, actionCommand, Calendar.getInstance().getTimeInMillis(), 0);
    				((ActionListener) listeners[i + 1]).actionPerformed(e);
    			}
    		}
    	}
     
    	public void addActionListener(ActionListener l) {
    		listenerList.add(ActionListener.class, l);
    	}
     
    	public void removeActionListener(ActionListener l) {
    		listenerList.remove(ActionListener.class, l);
    	}
    }

    2.CountDown :


    Java Code:
    import java.awt.event.ActionListener;
     
    public class CountDown implements Runnable {
     
    	private Thread timer;
    	private int delay;
    	private int timePassed = 0;
    	private ActionSupport actionSupport = new ActionSupport(this);
     
    	public CountDown(int delay) {
    		this.delay = delay;
    		timer = new Thread(this);
    		timer.setName("Timer");
    		timer.start();
    	}
     
    	public void addActionListener(ActionListener l) {
    		actionSupport.addActionListener(l);
    	}
     
    	public void removeActionListener(ActionListener l) {
    		actionSupport.removeActionListener(l);
    	}
     
    	
    	public void run() {
    		boolean ended = false;
    		while (Thread.currentThread().equals(timer) && !ended) {
    			try {
    				Thread.sleep(999);
    				timePassed++;
    				if (timePassed >= delay) {
    					actionSupport.fireActionPerformed("ended");
    					ended = true;
    				} else {
    					actionSupport.fireActionPerformed("tick");
    				}
    			} catch (InterruptedException e) {
    				e.printStackTrace();
    			}
    		}
    	}
     
    	public int getDelay() {
    		return delay;
    	}
     
    	public int getTimePassed() {
    		return timePassed;
    	}
     
    }


    3. MainPanel : The gui class


    Java Code:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
     
    public class MainPanel extends JPanel implements ActionListener {
     
    	private JLabel label;
    	private CountDown countDown;
     
    	public MainPanel() {
    		countDown = new CountDown(10);
    		countDown.addActionListener(this);
    		setSize(100, 100);
    		setLayout(new BorderLayout());
    		add(getLabel(), BorderLayout.CENTER);
    	}
     
    	
    	public void actionPerformed(ActionEvent e) {
    		if (e.getActionCommand().equals("ended")) {
                            label.setText(String.valueOf(countDown.getDelay() - countDown.getTimePassed()));
    			JOptionPane.showMessageDialog(null, "Time Over");
    		} else {
    			label.setText(String.valueOf(countDown.getDelay() - countDown.getTimePassed()));
    		}
    	}
     
    	public JLabel getLabel() {
    		if (label == null) {
    			label = new JLabel();
    			label.setText(String.valueOf(countDown.getDelay()));
    		}
    		return label;
    	}
     
    	public static void main(String[] args) {
    		JFrame frame = new JFrame("CountDown");
    		MainPanel panel = new MainPanel();
    		frame.setSize(panel.getSize());
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setContentPane(panel);
    		frame.setVisible(true);
    	}
    }
    4) And this is the class were i call the CountDown timer

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class JPasswordField1 {
        public static void main(String[] argv) {
            final JFrame frame = new JFrame("JPassword");
    
            JLabel jlbPassword = new JLabel("Enter the password: ");
            JPasswordField jpwName = new JPasswordField(10);
            jpwName.setEchoChar('*');
            jpwName.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JPasswordField input = (JPasswordField)e.getSource();
                    char[] password = input.getPassword();
                    if (isPasswordCorrect(password)) {
                        JOptionPane.showMessageDialog(frame, "Correct  password.");
                         JOptionPane.showMessageDialog(null, "This is a Geography Quiz");
                         JOptionPane.showMessageDialog(null, "Good Luck");
                         JOptionPane.showMessageDialog(null, "You got 50 seconds to answer all the questions in each quiz");
                         GQ frame = new GQ();
                         frame.setVisible(true);
                         MainPanel mp = new MainPanel();  // calling the class for the count down timer
                         mp.setVisible(true);
                        
            
                    
                    } else {
                        JOptionPane.showMessageDialog(frame, "Sorry. Try again.",
                            "Error Message", JOptionPane.ERROR_MESSAGE);
                    }
                }
            
            
            
            });
    
            JPanel jplContentPane = new JPanel(new BorderLayout());
            jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            jplContentPane.add(jlbPassword, BorderLayout.WEST);
            jplContentPane.add(jpwName, BorderLayout.CENTER);
    
            frame.setContentPane(jplContentPane);
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) { System.exit(0); }
            });
            frame.pack();
            frame.setVisible(true);
        }
    
        private static boolean isPasswordCorrect(char[] inputPassword) {
            char[] actualPassword = { 'q', 'u', 'i', 'z' };
            if (inputPassword.length != actualPassword.length)
                return false;		//Return false if lengths are unequal
            for (int i = 0;  i < inputPassword.length; i ++)
                if (inputPassword[i] != actualPassword[i])
                    return false;
            return true;
        }
    
        
    
    }
    Thanks for helping. :)

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Calendar;
    import javax.swing.*;
    import javax.swing.event.*;
    
    public class JPF1 implements ActionListener {
        static GQ gq;
    
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            System.out.println("ac = " + ac);
            if(ac.equals("ended")) {
                System.out.println("time is up - tell GQ instance gq " +
                                   "so it can skip to the results...");
                // You will have to make arrangements for this in GQ.
                //gq.stopAndShowResults();
            }
        }
    
        public static void main(String[] argv) {
            final JPF1 appRef = new JPF1();
            final JFrame frame = new JFrame("JPassword");
    
            JLabel jlbPassword = new JLabel("Enter the password: ");
            JPasswordField jpwName = new JPasswordField(10);
            jpwName.setEchoChar('*');
            jpwName.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JPasswordField input = (JPasswordField)e.getSource();
                    char[] password = input.getPassword();
                    if (isPasswordCorrect(password)) {
                        JOptionPane.showMessageDialog(frame, "Correct  password.");
                        JOptionPane.showMessageDialog(null,
                                              "This is a Geography Quiz");
                        JOptionPane.showMessageDialog(null, "Good Luck");
                        JOptionPane.showMessageDialog(null, "You got 50 seconds " +
                               "to answer all the questions in each quiz");
                        gq = new GQ();
                        gq.setVisible(true);
                        // calling the class for the count down timer
                        MP mp = new MP();
                        mp.addCountDownListener(appRef);
                        mp.setVisible(true);
                    } else {
                        JOptionPane.showMessageDialog(frame, "Sorry. Try again.",
                            "Error Message", JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
    
            JPanel jplContentPane = new JPanel(new BorderLayout());
            jplContentPane.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            jplContentPane.add(jlbPassword, BorderLayout.WEST);
            jplContentPane.add(jpwName, BorderLayout.CENTER);
    
            frame.setContentPane(jplContentPane);
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) { System.exit(0); }
            });
            frame.pack();
            frame.setVisible(true);
        }
    
        private static boolean isPasswordCorrect(char[] inputPassword) {
            char[] actualPassword = { 'q', 'u', 'i', 'z' };
            if (inputPassword.length != actualPassword.length)
                return false;		//Return false if lengths are unequal
            for (int i = 0;  i < inputPassword.length; i ++)
                if (inputPassword[i] != actualPassword[i])
                    return false;
            return true;
        }
    }
     
    class MP extends JPanel implements ActionListener {
        private JLabel label;
        private CountDown countDown;
    
        public MP() {
            countDown = new CountDown(10);
            countDown.addActionListener(this);
            setSize(100, 100);
            setLayout(new BorderLayout());
            add(getLabel(), BorderLayout.CENTER);
        }
    
        public void actionPerformed(ActionEvent e) {
            if (e.getActionCommand().equals("ended")) {
                label.setText(String.valueOf(countDown.getDelay() -                    
    
                          countDown.getTimePassed()));
                JOptionPane.showMessageDialog(null, "Time Over");
            } else {
                label.setText(String.valueOf(countDown.getDelay() -                    
    
                          countDown.getTimePassed()));
            }
        }
     
        public JLabel getLabel() {
            if (label == null) {
                label = new JLabel();
                label.setText(String.valueOf(countDown.getDelay()));
                label.setHorizontalAlignment(JLabel.CENTER);
                label.setFont(label.getFont().deriveFont(20f));
            }
            return label;
        }
    
        protected void addCountDownListener(ActionListener al) {
            countDown.addActionListener(al);
        }
     
        public static void main(String[] args) {
            JFrame frame = new JFrame("CountDown");
            MP panel = new MP();
            frame.setSize(panel.getSize());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(panel);
            frame.setVisible(true);
        }
    }

  3. #3
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default

    Thanks a lot for your help. I really appreciate it. I tried to arrange the code in the GQ as you have told me, but still there's something wrong, because its not stopping and displaying the result. Can you pls help me figure out the problem? Thanks a lot. :)

    This is the code in the GQ class:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.util.Calendar;
     
    public class GQ extends JFrame implements ActionListener {
        private static final int FRAME_WIDTH = 140;
        private static final int FRAME_HEIGHT = 160;
        private static final int FRAME_X_ORIGIN = 70;
        private static final int FRAME_Y_ORIGIN = 50;
        AnswerStore answerStore = new AnswerStore();
    
     
        
        public static void main (String[] args) {
            
            
           
    
            JOptionPane.showMessageDialog(null, "This is a Geography Quiz");
            JOptionPane.showMessageDialog(null, "Good Luck");
     
            
     
                GQ frame = new GQ();
                frame.setVisible(true);
           
        }
     
        public GQ() {
            Container contentPane;
            JButton button1, button2, button3, button4, button5;
     
            setSize (FRAME_WIDTH, FRAME_HEIGHT);
            setTitle("Geography Quiz");
            setLocation(FRAME_X_ORIGIN, FRAME_Y_ORIGIN);
     
            contentPane = getContentPane();
            contentPane.setBackground(Color.pink);
            contentPane.setLayout(new FlowLayout());
     
            button1 = new JButton("Plate Tectonics");
            button2 = new JButton("Rivers");
            button3 = new JButton("Rocks");
            button4 = new JButton("Quit");
     
            contentPane.add(button1);
            contentPane.add(button2);
            contentPane.add(button3);
            contentPane.add(button4);
        
            button1.addActionListener(this);
            button1.setActionCommand("b1");
            button2.addActionListener(this);
            button2.setActionCommand("b2");
            button3.addActionListener(this);
            button3.setActionCommand("b3");
            button4.addActionListener(this);
            button4.setActionCommand("b4");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
        }
      
         public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            String[] questions = null;
            String[] answers = null;
            if (ac.equals("b1")) {
                questions = readFile("plate_tectonics.txt");
                answers = answerStore.tectonicAnswers;
            } else if(ac.equals("b2")) {
                questions = readFile("rivers.txt");
                answers = answerStore.riverAnswers;
            } else if(ac.equals("b3")) {
                questions = readFile("rocks.txt");
                answers = answerStore.rockAnswers;
            } else if (ac.equals("b4")) {
                System.exit(0);
            }
              else if(ac.equals("ended")) {
              GQ.stopAndShowResults(); //my problem is somewhere here, because altough 
             //it displays the message "time is over" the program isn't stopping and displaying the results. 
            }
             askQuestions(questions, answers);
           
           
        }
           
        
    
        
     
        private String[] readFile(String path) {
            Scanner s = null;
            StringBuilder sb = new StringBuilder();
            String separator = "\n";
            try {
                s = new Scanner(new BufferedReader(new FileReader(path)));
    
                while (s.hasNext()) {
                    sb.append(s.nextLine() + separator);
    
                }
            } catch(IOException e) {
                System.out.println("read error: " + e.getMessage());
            } finally {
                if (s != null) 
                    s.close();
    
            }
           
            System.out.println("sb = " + sb.toString());
            System.out.printf("sb.split = %s%n", Arrays.toString(sb.toString().split("\\n")));
            return sb.toString().split("\\n");
        }
     
        private void askQuestions(String[] questions, String[] answers) {
           
            System.out.printf("questions = %s%nanswers = %s%n", // debugging
                               Arrays.toString(questions),
                               Arrays.toString(answers));
            int count = 0;
            int point = 0;
            for(int j = 0; j < questions.length; j++) {
                String input = JOptionPane.showInputDialog(null, questions[j]);
                if(answers[j].equals(input))
                  { 
                    count++;
                    point++;
                }   
                }
                JOptionPane.showMessageDialog(null, "You answered " + count +
                                          " out of " + questions.length +
                                          " questions correctly.");
                JOptionPane.showMessageDialog(null, "Your Geography Quiz score is " + ((point*100)/10) + " % ");
            
              if(point>=0 && point<=3)
              {
                 
                  JOptionPane.showMessageDialog(null, "You need to Improve");
               }
               
               
             if(point>=4 && point<=7)
              {
                 
                  JOptionPane.showMessageDialog(null, "Good");
               }
               
               if(point>=8 && point<=10)
              {
                 
                  JOptionPane.showMessageDialog(null, "You did Great");
               }
                                        
          }
        }
     
    class AnswerStore  {
        String[] tectonicAnswers = {
            "Hellenic", "destructive", "100km", "Italy", "Wegner",
            "Mariana", "Sicily", "created", "constructive", "Mediterranean"
        };
        
        String[] riverAnswers = {
            "Gorges", "Meanders", "Levees", "Yes", "Less Economic Developed Countries",
            "crescent shaped lakes", "More Economic Developed Countries", "No", "River Discharge", "No"
        };
        
        String[] rockAnswers = {
            "40km", "Igneous Rock", "Sedimentary", "Basalt", "Organic",
            "pressure", "Oolites", "Igneous", "dark black", "basalt"
        };
    
     
    
    }
    Thanks again for your help. You are very helpful and i really appreciate it. :)

  4. #4
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    You want to devise a way for the app, here JPF1, to message the CQ class that it is time to stop asking questions and give the results. So you can add a method to the CQ class which the JPF1 class can call by using its reference to its instance of CQ, viz, "cq". Then you want to devise a way to do this (make the change from questions to results) in CQ. As a pseudo code suggestion you might try something like this to get started:
    Java Code:
    class GQ extends JFrame implements ActionListener {
        ...
        public void actionPerformed(ActionEvent e) {
            ...
            } else if (ac.equals("b4")) {
                System.exit(0); 
            }
             askQuestions(questions, answers);
        }
    
        public void stopAndShowResults() {
            timeForMore = false;
        }
    
        ...
    
        private void askQuestions(String[] questions, String[] answers) {
            ...
            for(int j = 0; j < questions.length; j++) {
                if(!timeForMore)
                    break;
                String input = JOptionPane.showInputDialog(null, questions[j]);
                if(answers[j].equals(input)) { 
                    count++;
                    point++;
                }   
            }
            ...
    using the classes/code in reply 2.

  5. #5
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default

    Yeah, i understood clearly now. Thanks a lot. But my problem now is in this part of code:


    Java Code:
    if(!timeForMore)
                break;
    Because when i place it right after the for loop its not opening the textfiles as i click for example on the platetectonics quiz. So i think that its breaking immediately, before opening the questions, and when i place that part of code after the other "if part" like the code below, its only opening one question and displays the results, where as its supposed to display the 10 questions one after the other until time is over. I think this is happening because of the for loop.

    Java Code:
    for(int j = 0; j < questions.length; j++) {
               
              
              
                String input = JOptionPane.showInputDialog(null, questions[j]);
                
                if(answers[j].equals(input))
                  { 
                    count++;
                    point++;
                }
                if(!timeForMore)
                break;
    Thanks again for your time in helping me, i really owe you a lot! :)

  6. #6
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    You'll want to reset the "timeForMore" boolean to true before each timed question–and–answer session.

  7. #7
    saytri is offline Member
    Join Date
    Dec 2007
    Posts
    34
    Rep Power
    0

    Default

    Ok thanks a lot. Thanks to your help i have achieved doing it. Thanks again. :-)
    Last edited by saytri; 01-09-2008 at 05:35 PM.

Similar Threads

  1. Problem to ToolTip in Java 3d
    By roshithmca in forum AWT / Swing
    Replies: 1
    Last Post: 02-05-2008, 03:46 AM
  2. Problem in java
    By saytri in forum New To Java
    Replies: 4
    Last Post: 01-16-2008, 10:09 PM
  3. Problem with timer in java
    By paul in forum Advanced Java
    Replies: 3
    Last Post: 07-26-2007, 10:18 AM
  4. JAVA if problem
    By toby in forum New To Java
    Replies: 2
    Last Post: 07-25-2007, 07:58 PM
  5. java SE 6 problem
    By techlance in forum Java Applets
    Replies: 1
    Last Post: 06-28-2007, 10:10 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •