I am in the middle of creating a children's board game, that asks random maths questions and players move if they answer right. I have a main BoardGUI class that includes 2 panels. One for the board, and one for the questions.
I'm having trouble with the Question panel. I'm reading in questions from a text file and saving each question as an object within an array. The issue is I can answer one question correctly and it will refresh the question with a new one, however doesn't keep doing this.
I'll paste the QuestionGUI class, as I think this is the one with issues to do with generating the same question/answers from a random number.
public class QuestionGUI extends JPanel implements ActionListener {
JLabel question;
JButton btnAnswers[];
Reader r1 = new Reader();
Questions q1 = new Questions();
Random rand = new Random();
boolean answered;
int random = rand.nextInt(r1.ArraySize());
int random2 = rand.nextInt(r1.ArraySize());
int length = q1.getArrayItem(random).getAnswers().length;
public QuestionGUI() {
questionInit(random);
}
public void questionInit(int randomNum) {
this.random = randomNum;
//gets the answers from the array obj
String[] answers = q1.getArrayItem(random).getAnswers();
//sets the question from question of array obj (same obj as answers I assumed, using random num)
question = new JLabel("<html>" + (q1.getArrayItem(random).getQuestion()) + "</html>", SwingConstants.CENTER);
question.setPreferredSize(new Dimension(280, 100));
add(question);
btnAnswers = new JButton[length];
for (int i = 0; i < length; i++) {
btnAnswers[i] = new JButton(answers[i]);
btnAnswers[i].setPreferredSize(new Dimension(280, 60));
btnAnswers[i].addActionListener(this);
add(btnAnswers[i]);
}
}
@Override
public void actionPerformed(ActionEvent e) {
//sets the correct answers to question also using the random num
String[] correctAnswers = q1.getArrayItem(random).getCorrectAnswers();
for (int i = 0; i < length; i++) {
if (e.getSource().equals(btnAnswers[i])) {
String tmp1 = btnAnswers[i].getText();
if (Arrays.asList(correctAnswers).contains(tmp1)) {
System.out.println("Correct");
removeAll();
revalidate();
answered = true;
questionInit(random2);
repaint();
} else {
answered = false;
}
}
}
}
public boolean getAnswered() {
return answered;
}
}
Aucun commentaire:
Enregistrer un commentaire