get selected radio button list in swing
Asked Answered
A

1

5

Im going to create multiple choice question application using java swing.I have created swing class with list of radio buttons inside separate jPanels.I need to find the selected radio button and make highlighted on correct answer when submit the button. but I cant get the selected radio button list in swing. can anyone suggest me a good solution ?

private void myInitComponents() {

    jLabel = new javax.swing.JLabel();
    setLayout(new BorderLayout());
    jButton1 = new javax.swing.JButton();

    QuestionDaoIF questionDao = new QuestionDao();

    List<Question> listOfQuestion = questionDao.getQuestion();
    jPanel2 = new javax.swing.JPanel();
    jPanel2.setLayout(new BoxLayout(jPanel2, BoxLayout.Y_AXIS));
    JScrollBar vbar = new JScrollBar(JScrollBar.VERTICAL, 30, 100, 0, 300);
    vbar.addAdjustmentListener(new MyAdjustmentListener());


    add(jLabel, BorderLayout.CENTER);
    jPanel2.setAutoscrolls(true);
    List<String> answerList = new ArrayList<>();
    List<Question> questionList = listOfQuestion ;
    Collections.shuffle(questionList);

    int i = 1;
    for (Question question : questionList) {

        QuestionPane pane = new QuestionPane();
        pane.getjTextPane1().setText("("+i+")  "+question.getQuestion());
        //genarate random answers
        genarateRandomAnswer(question, answerList, pane);

        jPanel2.add(pane);
        i++;
    }
    jButton1.setText("Submit");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    jPanel2.add(jButton1);
    //jPanel2.setBounds(100, 100, 800, 700);
    this.add(getJMainScrollPane());
    this.setTitle("Quizz");
    this.setSize(1000, 700);
    //pack();

}

    private JScrollPane getJMainScrollPane() {
    JScrollPane jMainScrollPane = new JScrollPane(jPanel2);
    jMainScrollPane.setViewportBorder(BorderFactory
            .createLineBorder(Color.GREEN));
    jMainScrollPane
            .applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    return jMainScrollPane;
}

private void genarateRandomAnswer(Question question, List<String> answerList, QuestionPane pane) {
    String answer1 = question.getCorrectAnswer();
    String answer2 = question.getWrongAnswer1();
    String answer3 = question.getWrongAnswer2();
    String answer4 = question.getWrongAnswer3();

    List<Answer> answrList = new ArrayList<>();

    Answer ans1 = new Answer();
    ans1.setAnswer(answer1);
    ans1.setCorrectAnswer(true);

    Answer ans2 = new Answer();
    ans2.setAnswer(answer2);
    ans2.setCorrectAnswer(false);

    Answer ans3 = new Answer();
    ans3.setAnswer(answer3);
    ans3.setCorrectAnswer(false);

    Answer ans4 = new Answer();
    ans4.setAnswer(answer4);
    ans4.setCorrectAnswer(false);

    answrList.add(ans1);
    answrList.add(ans2);
    answrList.add(ans3);
    answrList.add(ans4);

    Collections.shuffle(answrList);
    buttonGroup1 = new javax.swing.ButtonGroup();
    buttonGroup1.add(pane.getjRadioButton1());
    buttonGroup1.add(pane.getjRadioButton2());
    buttonGroup1.add(pane.getjRadioButton3());
    buttonGroup1.add(pane.getjRadioButton4());

    pane.getjRadioButton1().setText("(a) "+answrList.get(0).getAnswer());
    pane.getjRadioButton1().setHideActionText(answrList.get(0).isCorrectAnswer());
    pane.getjRadioButton2().setText("(b) "+answrList.get(1).getAnswer());
    pane.getjRadioButton2().setHideActionText(answrList.get(1).isCorrectAnswer());
    pane.getjRadioButton3().setText("(c) "+answrList.get(2).getAnswer());
    pane.getjRadioButton3().setHideActionText(answrList.get(2).isCorrectAnswer());
    pane.getjRadioButton4().setText("(d) "+answrList.get(3).getAnswer());
    pane.getjRadioButton4().setHideActionText(answrList.get(3).isCorrectAnswer());  
}

class MyAdjustmentListener implements AdjustmentListener {

    @Override
    public void adjustmentValueChanged(AdjustmentEvent e) {
       jLabel.setText("    New Value is " + e.getValue() + "      ");
        repaint();
    }
}
Acceleration answered 6/9, 2013 at 6:25 Comment(5)
Create a model of the question, which the UI can create the view of. Allow the view to set the selected answer back to the model...Battalion
please whats logics??? quesions are randomly displayed, where did you store previous selections??? in the JLabel only, getCorrectAnswer is hardcoded???Sheathe
I have already created QuestionUI in the QuestionPane class and I use its object hereAcceleration
For better help sooner, post an SSCCE.Mala
yes, questions and answers are randomly displayed, no, getCorrectAnswer() is the getter in the Question pojo and it stored the correct answer. I used separate Answer dto to set true to the correct answer and store it as setHideActionText()Acceleration
B
7

Create a QuestionAnswerPane which is capable of taking a reference to a Question model

This panel will be responsible for generating the view represented by the Question model and storing the user's response in it.

The QuestionAnswerPane should know what JRadioButton belongs to which answer. When the user selects one of the radio buttons, it will update the Question model with the answer that the user has selected.

When the user clicks Submit, you would simply look up each Question and retrieve the answer the user selected.

It also decouples the model from the UI making it easier to deal with. With this idea, you could actually check if all the questions have being answered for example. This could also be accomplished by adding something like a ChangeListener to the model

Updated with BASIC example

This is only an example designed to demonstrate the concept of the Question being the centralised controller/model

enter image description here

Which, based on the screen shot above, outputs...

The color of a banana?
          Your answer was : Yellow
    The correct answer is : Yellow
                  You are : Right
The utimate question of life the universe and every thing?
          Your answer was : Choclate
    The correct answer is : 42
                  You are : Wrong
Who's your daddy?
          Your answer was : R2D2
    The correct answer is : Darth Vadar
                  You are : Wrong
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.TitledBorder;

public class QuestionAnswer {

    public static void main(String[] args) {
        new QuestionAnswer();
    }

    public QuestionAnswer() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new QuestionsPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class QuestionsPane extends JPanel {

        public QuestionsPane() {

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            final List<Question> questions = new ArrayList<>(3);
            questions.add(new Question("The color of a banana?", 
                            new Answer("Yellow"),
                            new Answer("Pink"),
                            new Answer("Blue"),
                            new Answer("Orange")
                    ));
            questions.add(new Question("The utimate question of life the universe and every thing?", 
                            new Answer("42"),
                            new Answer("Sleep"),
                            new Answer("Choclate"),
                            new Answer("1024"),
                            new Answer("Microsoft"),
                            new Answer("Apple")
                    ));
            questions.add(new Question("Who's your daddy?", 
                            new Answer("Darth Vadar"),
                            new Answer("Anikin Skywalker"),
                            new Answer("Yoda"),
                            new Answer("Mace Windo"),
                            new Answer("Chewbacca"),
                            new Answer("R2D2")
                    ));

            for (Question q : questions) {

                add(new QuestionAnswerPane(q), gbc);

            }

            gbc.weighty = 1;
            add(new JPanel(), gbc);
            gbc.weighty = 0;
            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.CENTER;

            JButton submit = new JButton("Submit");
            submit.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    for (Question q : questions) {
                        System.out.println(q.getText());
                        System.out.println("\t      Your answer was : " + q.getSelectedAnswer());
                        System.out.println("\tThe correct answer is : " + q.getCorrectAnswer());
                        System.out.println("\t              You are : " + (q.isCorrectAnswer() ? "Right" : "Wrong"));
                    }
                }
            });

            add(submit, gbc);

        }

    }

    public class QuestionAnswerPane extends JPanel {

        public QuestionAnswerPane(Question question) {

            List<Answer> answers = new ArrayList<>(question.getWrongAnswers());
            answers.add(question.getCorrectAnswer());

            Collections.shuffle(answers);

            setBorder(new TitledBorder(question.getText()));
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;

            ButtonGroup bg = new ButtonGroup();
            for (Answer answer : answers) {

                JRadioButton rb = new JRadioButton(new AnswerAction(question, answer));
                bg.add(rb);
                add(rb, gbc);

            }
            gbc.weighty = 1;
            add(new JPanel(), gbc);

        }

    }

    public class AnswerAction extends AbstractAction {

        private final Question question;
        private final Answer answer;

        public AnswerAction(Question question, Answer answer) {
            this.question = question;
            this.answer = answer;
            putValue(NAME, answer.getText());
        }

        public Answer getAnswer() {
            return answer;
        }

        public Question getQuestion() {
            return question;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            getQuestion().setSelectedAnswer(answer);
        }

    }

    public class Question {

        private Answer correctAnswer;
        private List<Answer> wrongAnswers;
        private Answer selectedAnswer;

        private String text;

        public Question(String text, Answer correct, Answer... wrong) {
            wrongAnswers = new ArrayList<>(Arrays.asList(wrong));
            correctAnswer = correct;
            this.text = text;
        }

        public String getText() {
            return text;
        }

        public Answer getCorrectAnswer() {
            return correctAnswer;
        }

        public List<Answer> getWrongAnswers() {
            return Collections.unmodifiableList(wrongAnswers);
        }

        public Answer getSelectedAnswer() {
            return selectedAnswer;
        }

        public void setSelectedAnswer(Answer selectedAnswer) {
            this.selectedAnswer = selectedAnswer;
        }

        public boolean isCorrectAnswer() {
            Answer answer = getSelectedAnswer();
            Answer correct = getCorrectAnswer();
            return correct.equals(answer);
        }

        @Override
        public String toString() {
            return getText();
        }

    }

    public class Answer {

        private String text;

        public Answer(String text) {
            this.text = text;
        }

        public String getText() {
            return text;
        }

        @Override
        public String toString() {
            return getText();
        }

    }

}
Battalion answered 6/9, 2013 at 6:52 Comment(5)
you meant using Question model set the all attribute to QuestionAnswerPane, after the iterate QuestionAnswerPane and show questions ? I have a problem to getSelectedValue when I click the submit buttonAcceleration
No. I mean, allow the QuestionAnswerPane to set the "select answer from the user" BACK to the Question model, then you don't care about what state the UI is in...Battalion
I've added a conceptual concept of what I'm talking about. You should be able to see that the Question is the key, it holds all the information required to determine what the question is asking and what the user selected, all without relying on the UI in any way...I don't care where the answers come from or how they are formatted...Battalion
I have to display correct answer with question, so can you give me a small idea to mark a correct answer(highlighting radio button text) in the QuestionPane. main problem is I cant specifically select the extract question in ui.Acceleration
There's a few ways you could do it, in the QuestionAnswerPane, you would need to provide a method that could be used to highlight the answer (ie highlightCorrectNaswer). You would need to maintain a reference to the JRadioButton that represented the correct answer, you can do this in the loop that builds the buttons. In the main UI, you will need to maintain a list of the panels and there associated Questions, this can be achieved through a MapBattalion

© 2022 - 2024 — McMap. All rights reserved.