Gui Population w/ Rand function
Greetings,
I'm currently working on a project to create a Trivia game based on movie quotes. I have my code completed, all except the GUI. I'm a bit fuddled as to how to get my GUI to grab the randomly generated information and put it in the fields.
This is what I am envisioning:
I want to have a random question/quote pop up. Then I want 4 random answers to display below it, with Radio or CheckBoxes (which I still havent figured out how to). Once the person clicks their answer they can hit SUBMIT or ENTER, at that point I want it to display if they were correct, if they were NOT correct then display the correct answer and move onto the next question by clicking the NEXT button.
Enclosed is my code (I have a section at the beginning where I have started the process of the GUI code, but just got stumped). Any feedback would be greatly appreciated.
The GUI is a specific element that is required for this project (otherwise I'd just let leave it as is.)
import java.util.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.JOptionPane;
import java.io.*;
privateclass TriviaGameextends JFrame
{
privatestaticfinalint WIDTH = 400;
privatestaticfinalint HEIGHT = 300;
private JLabel
public TriviaGame()
{
setTitle("Movie Trivia!");
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
publicstaticvoid main(String[] args)
{
//identify variables
String player;
int totalQuestions = 15;
String question [] =new String[totalQuestions];
String correctAnswer [] =new String[totalQuestions];
String answerQuestion [] =new String[totalQuestions];
Random rand =new Random();
int qRand;
int qUsed[] =newint[10];
int aRand;
int fillRand;
int aUsed[] =newint[4];
boolean unique;
boolean used;
String questionAsked[] =new String[10];
String playersAnswerString;
int playersAnswer;
int score = 0;
int x;//counter
int y;//counter
int z;//counter
//input player's name
player = JOptionPane.showInputDialog("What is your Name?");
//read external file containing questions and answers
try
{
Scanner console =new Scanner(new FileReader("MovieQuotes.txt"));
console.useDelimiter("ZZ");
for(x=0;x<totalQuestions;x++)
{
question[x] = console.next();
correctAnswer[x] = console.next();
}
console.close();
}
catch (IOException ioe)
{
System.out.println("IO Exception");
}
//randomly determine questions to be asked
for(x=0;x<10;x++)//x is a counter for the outer loop
{
do
{
unique =true;
qRand = rand.nextInt(10);
for(y=0;y<x;y++)//y is a counter for the inner loop
{
//ensure that each question has not already been assigned to be asked
if(qRand == qUsed[y])
unique =false;
}
}
while (!unique);
questionAsked[x] = question[qRand];
answerQuestion[x] = correctAnswer[qRand];
qUsed[x] = qRand;
}
//print the quote
for(x=0;x<10;x++)//x is a counter for the outer loop
{
System.out.println(questionAsked[x]);
//print 4 possible answers
aRand = rand.nextInt(4);//determines placement of correctAnswer
for(y=0;y<4;y++)
{
if(aRand == y)//true prints correctAnswer
{
System.out.println((y+1) +") " + answerQuestion[x]);
aUsed[y] = aRand;
}
else//fills in remaining 3 slots with random false answers
{
do
{
used =false;
fillRand = rand.nextInt(totalQuestions);
if (answerQuestion[x] == correctAnswer[fillRand])
used =true;
for(z=0;z<y;z++)
{
if (aUsed[z] == fillRand)
used =true;
}
}
while (used);
aUsed[y] = fillRand;
System.out.println((y+1) +") " + correctAnswer[fillRand]);
}
}
//recieve answer from user and deterimine if it is correct
playersAnswerString = JOptionPane.showInputDialog("What movie is this quote from? Please answer 1, 2, 3, or 4");
playersAnswer = (Integer.parseInt(playersAnswerString) - 1);
if (playersAnswer == aRand)
{
score++;
System.out.println("Your answer was " + (playersAnswer + 1));
System.out.println("Correct");
System.out.println();
}
else
{
System.out.println("Your answer was " + (playersAnswer + 1));
System.out.println("Incorrect");
System.out.println("The correct answer is " + answerQuestion[x]);System.out.println();
}
}
//output player's score and judgement
System.out.println(player +", your score is " + score +" out of 10");
switch (score){
case 10:
System.out.println ("PERFECT!");
break;
case 9:
System.out.println ("Very Good. Your movie knowledge is above par.");
break;
case 8:
System.out.println ("Good. You only missed 2.");
break;
case 7:
System.out.println ("Average");
break;
default:
System.out.println ("Your movie knowledge could use some work.");
}
}
}
>
Ok. There's a syntax error right before the constructor, where you declare a type with no identifier.And is this an inner class? I notice that the class is declared private immediately after the imports, which makes me suspect that either something is missing or it's a mistake.
Also, try posting the contents of the text file as you have it. I see that it's a "ZZ" delimited file, but if I create one, I have no way of telling if it's identical to what you're using.
Joe
Joe_ha at 2007-7-29 13:21:51 >

Thanks Joe :)
I left the first part unfinished because I just blanked on how to organize it all.
Here is the text file contents: (very basic quotes)
Have you ever danced with the devil in the pale moon light?ZZBatmanZZWho's Keyser Soze?ZZThe Usual SuspectsZZThere is no spoonZZThe MatrixZZWhy a spoon, cousin?ZZRobin Hood: Prince of ThievesZZWhat do they call you? "Wheels"?ZZX-MenZZHe will bring them death, and they will love him for itZZGladiatorZZI'm gonna make him an offer he can't refuseZZThe GodfatherZZThat's no moon. It's a space stationZZStar WarsZZSo you think you've solved in fourteen days what they couldn't solve in two years?ZZStargateZZIs your father a ghost, or do you converse with the Almighty?ZZBraveheartZZSnakes. Why'd it have to be snakes?ZZRaiders of the Lost ArkZZI will take the Ring to MordorZZThe Lord of the Rings: The Fellowship of the RingZZThe other girls were blonde and delicate and I was a swarthy six-year-old with sideburnsZZMy Big Fat Greek WeddingZZGo back to Jersey Sonny. This is the City of the Angels and you haven't got any wingsZZL.A. ConfidentialZZOur friend T-bird won't be joining us this evening on account of a slight case of deathZZThe Crow
I understand how to create the physical structure of the GUI, but after that I get a bit fuzzy.
I tried to related it to the system.out.print or even JOptionPane but it doesn't seem to function that way.
Sorry for sounding dumb, this is my first big program I've created with a GUI.
I rethought my question maybe this will be a bit clearer.
How do I use ONE GUI Structure multiple times via a FOR LOOP and give that GUI Structure different arguments each iteration of the FOR LOOP?
That ultimately is what I'm looking for and realized my original question sounded befuddled.
Apologies, here is the updated code:
import java.util.*;
import java.util.Random;
import javax.swing.JOptionPane;
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class TriviaGame2
{
public static void main(String[] args)
{
//identify variables
String player;
int totalQuestions = 15;
String question [] = new String[totalQuestions];
String correctAnswer [] = new String[totalQuestions];
String answerQuestion [] = new String[totalQuestions];
String possAnswer [] = new String[4];
String outputStr;
Random rand = new Random();
int qRand;
int aRand;
int fillRand;
int aUsed [] = new int[4];
boolean unique;
boolean used;
String questionAsked[] = new String[10];
String playersAnswerString;
int playersAnswer;
int score = 0;
int x; //counter
int y; //counter
int z; //counter
//input player's name
player = JOptionPane.showInputDialog("What is your Name?");
//read external file containing questions and answers
try
{
Scanner console = new Scanner(new FileReader("MovieQuotes.txt"));
console.useDelimiter("ZZ");
for(x=0;x<totalQuestions;x++)
{
question[x] = console.next();
correctAnswer[x] = console.next();
}
console.close();
}
catch (IOException ioe)
{
System.out.println("IO Exception");
}
//randomly determine questions to be asked
for(x=0;x<10;x++)//x is a counter for the outer loop
{
do
{
unique = true;
qRand = rand.nextInt(totalQuestions);
for(y=0;y<x;y++)//y is a counter for the inner loop
{
//ensure that each question has not already been assigned to be asked
if(correctAnswer[qRand] == answerQuestion[y])
unique = false;
}
}
while (!unique);
questionAsked[x] = question[qRand];
answerQuestion[x] = correctAnswer[qRand];
}
//print the quote
for(x=0;x<10;x++)//x is a counter for the outer loop
{
System.out.println(questionAsked[x]);
//print 4 possible answers
aRand = rand.nextInt(4);//determines placement of correctAnswer
for(y=0;y<4;y++)
{
if(aRand == y)//true prints correctAnswer
{
possAnswer[y] = answerQuestion[x];
}
else //fills in remaining 3 slots with random false answers
{
do
{
used = false;
fillRand = rand.nextInt(totalQuestions);
if (answerQuestion[x] == correctAnswer[fillRand])
used = true;
for(z=0;z<y;z++)
{
if (aUsed[z] == fillRand)
used = true;
}
}
while (used);
possAnswer[y] = correctAnswer[fillRand];
aUsed[y] = fillRand;
}
}
//recieve answer from user and deterimine if it is correct
playersanswer = GooeyQuestion(QuestionAsked[x], possAnswer[1], possAnswer[2], possAnswer[3], possAnswer[4]);
if (playersAnswer == aRand)
{
score++;
System.out.println("Your answer was " + (playersAnswer + 1));
System.out.println("Correct");
System.out.println();
}
else
{
System.out.println("Your answer was " + (playersAnswer + 1));
System.out.println("Incorrect");
System.out.println("The correct answer is " + answerQuestion[x]);System.out.println();
}
}
//output player's score and judgement
System.out.println(player + ", your score is " + score + " out of 10");
switch (score) {
case 10:
System.out.println ("PERFECT!");
break;
case 9:
System.out.println ("Very Good. Your movie knowledge is above par.");
break;
case 8:
System.out.println ("Good. You only missed 2.");
break;
case 7:
System.out.println ("Average");
break;
default:
System.out.println ("Your movie knowledge could use some work.");
}
}
public static String GooeyQuestion(String Q, String A, String B, String C, String D)
{
public class Gooey extends JFrame
{
private static final int WIDTH = 400;
private static final int HEIGHT = 300;
private JLabel Quote;
public JButton Ans1, Ans2, Ans3, Ans4;
public Gooey()
{
Quote = new JLabel(Q);
Ans1 = new JButton(A);
A1H = new A1handler();
Ans1.addActionListener(A1H);
Ans2 = new JButton(B);
A2H = new A2handler();
Ans2.addActionListener(A2H);
Ans3 = new JButton(C);
A3H = new A3handler()
Ans3.addActionListener(A3H);
Ans4 = new JButton(D);
A4H = new A4handler();
Ans4.addActionListener(A4H);
Container pane = getContentPane();
pane.setLayout(new GridLayout(5, 1));
pane.add(Quote);
pane.add(Ans1);
pane.add(Ans2);
pane.add(Ans3);
pane.add(Ans4);
}
private class A1handler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
return A;}}
private class A2handler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
return B;}}
private class A3handler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
return C;}}
private class A4handler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
return D;}}
Gooey gooeyObject = new Gooey();
}
>
your code have bunch of errors. what exactly movies.txt contains and what are you trying to accomplish?
you have used lots of arrays and i am sure you are lost also like i am.
The movie.txt info can be located two posts above this one.
My intent is also explained in the original post. But my main goal is to create a simple GUI that generates a random movie quote, and 4 random answers. The player answers 10 questions. Thats it really :(
Yeah I thought the array's would be the best way to get random info in without writing an excessive amount of code :( So much for that theory! LOL
Having a huge main method with a bunch of nexted blocks is bad design and makes for very hard debugging. Divide and conquor.
I'd love to, but I have no idea how at this point. Thus the reason I am here, hoping for some structure pointers or maybe a suggestion as to better way to develop the methods.
ok. your first question in the txt file is ?
Q) Have you ever danced with the devil in the pale moon light?
1) Batman
2) Who's Keyser Soze?
3) The Usual Suspects
4) There is no spoon
Am i right?
No, the text file only has Question / correct answer / Question / correct answer....etc.
My trouble is the user defined method "Gooey" I cant seem to get the GUI functioning properly. I'm guessing it is because I'm not using public, private, static, void, whatever correctly
Right now my first compling error is
"Illegal start of expression" refering to the line
public class Gooey extends JFrame
i am just going to submit a demo. may be after that you might want to re think. note i am also not good in swing.
May be this program might be a little help for you. Just to give you an idea about swing. note i am also not good so learning never stops.
RandomGame.java
public class RandomQuestion {
private String question;
private String[] option;
private String answer;
public RandomQuestion(){}
public RandomQuestion(String question, String[] option, String answer) {
this.question = question;
this.answer = answer;
this.option = new String[4];
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
public void setQuestion(String aQues) {
question = aQues;
}
public void setAnswer(String aAns) {
answer = aAns;
}
public String getOptions() {
return option.toString();
}
}
PlayingGame.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;
public class PlayingGame extends JFrame implements ActionListener, ItemListener{
private JButton confirm = new JButton("Confirm"),
next = new JButton("next"),
previous = new JButton("previous");
private JLabel answer;
private RandomQuestion ques;
private List<RandomQuestion> q;
private JTextField questionField;
private JPanel commands, radioPanel, buttonPanel;
private String[] questions = {"Keanu Reeeves?", "Stevel Spielberg?", "Harry Potter?", "Sci Fi?"};
private String[] answer1 = {"Matrix", "Jaws", "Harry", "Daywatch"};
private String correctAnswer = answer1[0];
private String correctAnswer1 = answer1[1];
private String correctAnswer2 = answer1[2];
private String correctAnswer3 = answer1[3];
private JRadioButton[] radioButton;
private int index = 0;
//private ButtonGroup group;
private List<RandomQuestion> list;
public static void main(String[] args) {
PlayingGame frame = new PlayingGame();
frame.setVisible(true);
}
public PlayingGame() {
// TODO Auto-generated method stub
ButtonGroup group = new ButtonGroup();
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
setSize(400,300);
confirm.addActionListener(this);
next.addActionListener(this);
previous.addActionListener(this);
radioPanel = new JPanel(new GridLayout(0,1));
radioPanel.setBorder(BorderFactory.createTitledBorder("Pick Your choice"));
radioButton = new JRadioButton[answer1.length];
buttonPanel = new JPanel(new FlowLayout());
for(int i=0; i<radioButton.length; i++) {
radioButton[i] = new JRadioButton(answer1[i]);
radioButton[i].addItemListener(this);
group.add(radioButton[i]);
radioPanel.add(radioButton[i]);
}
radioButton[0].setSelected(true);
list = new ArrayList><RandomQuestion>();
answer = new JLabel("Answer");
questionField = new JTextField(20);
questionField.setText(questions[0]);
//questionField.setEditable(false);
//setVisible(true);
commands = new JPanel(new FlowLayout());
commands.add(questionField);
commands.add(confirm);
buttonPanel.add(next);
buttonPanel.add(previous);
buttonPanel.add(answer);
contentPane.add(commands, BorderLayout.NORTH);
contentPane.add(radioPanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
list.add(new RandomQuestion(questions[0], answer1, correctAnswer));
list.add(new RandomQuestion(questions[1], answer1, correctAnswer1));
questionField.setText(list.get(index).getQuestion());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
String favorite = null;
int i=0;
if(source==confirm)
{
while(favorite==null) {
if(radioButton[i].isSelected()) {
favorite = radioButton[i].getText();
}
i++;
answer.setText("You selected " + favorite);
}
} else if(source==next) {
goNext();
}
else if(source==previous) {
goPrevious();
}
}
public void itemStateChanged(ItemEvent e) {
JRadioButton source = (JRadioButton)e.getSource();
String state;
if(e.getStateChange()== ItemEvent.SELECTED) {
state = "is selected";
} else {
state = "Is deselected";
}
}
public void goNext() {
if( index < list.size() - 1 ) {
index++;
questionField.setText(list.get(index).getQuestion());
}
}
public void goPrevious() {
if(index > 0) {
index--;
questionField.setText(list.get(index).getQuestion());
}
}
}
Good luck. Overall nice assignment. i wish i have time to do it as you said but may be later on cheers.
Message was edited by:
lrngjava
