|
|
Welcome to the Java Forums.
You are currently viewing our boards as a guest which gives you limited access to view most discussions and access our other features. By joining our free community, you will:
- have access to post topics
- communicate privately with other members (PM)
- not see advertisements between posts
- have the possibility to earn one of our surprises if you are an active member
- access many other special features that will be introduced later.
Registration is fast, simple and absolutely free so please, join our community today!
If you have any problems with the registration process or your account login, please contact us.
|
|

01-07-2008, 10:21 PM
|
|
Member
|
|
Join Date: Dec 2007
Posts: 34
|
|
|
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:
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 :
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
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
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. 
|
|

01-08-2008, 03:10 AM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,189
|
|
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);
}
}
|
|

01-08-2008, 03:33 PM
|
|
Member
|
|
Join Date: Dec 2007
Posts: 34
|
|
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:
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. 
|
|

01-08-2008, 10:31 PM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,189
|
|
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:
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.
|
|

01-08-2008, 11:57 PM
|
|
Member
|
|
Join Date: Dec 2007
Posts: 34
|
|
Yeah, i understood clearly now. Thanks a lot. But my problem now is in this part of code:
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.
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! 
|
|

01-09-2008, 02:55 AM
|
|
Senior Member
|
|
Join Date: Jul 2007
Posts: 1,189
|
|
|
You'll want to reset the "timeForMore" boolean to true before each timed question–and–answer session.
|
|

01-09-2008, 05:13 PM
|
|
Member
|
|
Join Date: Dec 2007
Posts: 34
|
|
|
Ok thanks a lot. Thanks to your help i have achieved doing it. Thanks again. :-)
Last edited by saytri : 01-09-2008 at 06:35 PM.
|
|
| Thread Tools |
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|
|