Well, you can't quite work with a custom input dialog like that. There is a way to do it with an Object array for responses, but if you want radio buttons you need to create your own custom dialog. Just for the heck of it, I wrote up one way you could put this all together with JDialogs. Of course, you could probably do it a bit easier with a simple panel. Perhaps this will give you some ideas to work from (the simple BoxLayout is pretty awful)
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.swing.*;
public class QuizFourBib extends JDialog {
List<Question> questions = new ArrayList<Question>();
int score=0;
ButtonGroup group = new ButtonGroup();
JButton btnOk = new JButton("Ok");
public QuizFourBib(){
super();
setModal(true);
setLayout(new BoxLayout(getContentPane(),BoxLayout.Y_AXIS));
btnOk.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
questions.add(new Question("Who killed Goliath?", new String[]{"David", "Saul"}, "David"));
questions.add(new Question("Where was Moses born?", new String[]{"Egypt","Samaria"}, "Egypt"));
}
public int startQuiz(){
int score=0;
for (Question q : questions){
displayQuestion(q);
if (group.getSelection().getActionCommand().equals(q.getCorrectAnswer())){
score++;
}
}
dispose();
return score;
}
private void displayQuestion(Question q){
getContentPane().removeAll();
for (Enumeration buttonGroup=group.getElements(); buttonGroup.hasMoreElements(); ){
group.remove((AbstractButton)buttonGroup.nextElement());
}
JLabel questionText = new JLabel(q.getQuestion());
getContentPane().add(questionText);
for (String answer : q.getAnswers()){
JRadioButton radio = new JRadioButton(answer);
radio.setActionCommand(answer);
group.add(radio);
getContentPane().add(radio);
}
getContentPane().add(btnOk);
pack();
setVisible(true);
}
public static void main(String args[]) {
QuizFourBib quiz = new QuizFourBib();
int score = quiz.startQuiz();
JOptionPane.showMessageDialog(null,"Your score: "+score,"",JOptionPane.INFORMATION_MESSAGE);
}
class Question {
String question="";
String[] answers;
String correctAnswer;
public Question(String question, String[] possibleAnswers, String correctAnswer){
this.question = question;
this.answers = possibleAnswers;
this.correctAnswer = correctAnswer;
}
public String getQuestion() {
return question;
}
public String[] getAnswers() {
return answers;
}
public String getCorrectAnswer() {
return correctAnswer;
}
}
} Ezzaral
Posting Genius
Moderator
15,986 posts since May 2007
Reputation Points: 3,250
Solved Threads: 847