得到摆动选定的单选按钮列表 [英] get selected radio button list in swing

查看:169
本文介绍了得到摆动选定的单选按钮列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要去创建使用Java swing.I选择题应用程序创建摆动类单选按钮列表内单独jPanels.I需要找到选定的单选按钮,提交按钮时正确的答案使高亮。但我不能得到摆动选定的单选按钮列表。任何人都可以建议我一个很好的解决方案吗?

 私人无效myInitComponents(){    JLabel的新= javax.swing.JLabel中的();
    的setLayout(新的BorderLayout());
    的jButton1 =新javax.swing.JButton中的();    QuestionDaoIF questionDao =新QuestionDao();    清单<问题> listOfQuestion = questionDao.getQuestion();
    jPanel2 =新javax.swing.JPanel中();
    jPanel2.setLayout(新的BoxLayout(jPanel2,BoxLayout.Y_AXIS));
    JScrollBar的直条=新的JScrollBar(JScrollBar.VERTICAL,30,100,0,300);
    vbar.addAdjustmentListener(新MyAdjustmentListener());
    添加(JLabel的,BorderLayout.CENTER);
    jPanel2.setAutoscrolls(真);
    清单<串GT; answerList =新的ArrayList<>();
    清单<问题> questionList = listOfQuestion;
    Collections.shuffle(questionList);    INT I = 1;
    对于(问问题:questionList){        QuestionPane窗格=新QuestionPane();
        pane.getjTextPane1()的setText((+ I +)+ question.getQuestion())。
        // genarate随机答案
        genarateRandomAnswer(问题,answerList,窗格);        jPanel2.add(面板);
        我++;
    }
    jButton1.setText(提交);
    jButton1.addActionListener(新java.awt.event.ActionListener(){
        公共无效的actionPerformed(EVT java.awt.event.ActionEvent中){
            jButton1ActionPerformed(EVT);
        }
    });    jPanel2.add(的jButton1);
    //jPanel2.setBounds(100,100,800,700);
    this.add(getJMainScrollPane());
    this.setTitle(QUIZZ);
    this.setSize(1000,700);
    //包();}    私人JScrollPane的getJMainScrollPane(){
    JScrollPane的jMainScrollPane =新JScrollPane的(jPanel2);
    jMainScrollPane.setViewportBorder(BorderFactory
            .createLineBorder(Color.GREEN));
    jMainScrollPane
            .applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
    返回jMainScrollPane;
}私人无效genarateRandomAnswer(问题问题,列表<串GT; answerList,QuestionPane窗格){
    串ANSWER1 = question.getCorrectAnswer();
    串ANSWER2 = question.getWrongAnswer1();
    串ANSWER3 = question.getWrongAnswer2();
    串answer4 = question.getWrongAnswer3();    清单<应答和GT; answrList =新的ArrayList<>();    答ANS1 =新的答案();
    ans1.setAnswer(ANSWER1);
    ans1.setCorrectAnswer(真);    答ANS2 =新的答案();
    ans2.setAnswer(ANSWER2);
    ans2.setCorrectAnswer(假);    答ANS3 =新的答案();
    ans3.setAnswer(ANSWER3);
    ans3.setCorrectAnswer(假);    答ANS4 =新的答案();
    ans4.setAnswer(answer4);
    ans4.setCorrectAnswer(假);    answrList.add(ANS1);
    answrList.add(ANS2);
    answrList.add(ANS3);
    answrList.add(ANS4);    Collections.shuffle(answrList);
    buttonGroup1 =新javax.swing.ButtonGroup();
    buttonGroup1.add(pane.getjRadioButton1());
    buttonGroup1.add(pane.getjRadioButton2());
    buttonGroup1.add(pane.getjRadioButton3());
    buttonGroup1.add(pane.getjRadioButton4());    pane.getjRadioButton1()的setText((一)+ answrList.get(0).getAnswer())。
    pane.getjRadioButton1()setHideActionText(answrList.get(0).isCorrectAnswer())。
    pane.getjRadioButton2()的setText((二)+ answrList.get(1).getAnswer())。
    pane.getjRadioButton2()setHideActionText(answrList.get(1).isCorrectAnswer())。
    pane.getjRadioButton3()的setText((三)+ answrList.get(2).getAnswer())。
    pane.getjRadioButton3()setHideActionText(answrList.get(2).isCorrectAnswer())。
    pane.getjRadioButton4()的setText((四)+ answrList.get(3).getAnswer())。
    pane.getjRadioButton4()setHideActionText(answrList.get(3).isCorrectAnswer())。
}类MyAdjustmentListener实现的AdjustmentListener {    @覆盖
    公共无效adjustmentValueChanged(的AdjustmentEvent E){
       jLabel.setText(新值+ e.getValue()+);
        重绘();
    }
}


解决方案

创建一个 QuestionAnswerPane 这是能够采取一个问题<参考/ code>模式

这个小组将负责重新生成由问题模型psented $ P $视图和存储用户在它的响应。

QuestionAnswerPane 应该知道什么一个JRadioButton 属于哪个答案。当用户选择一个单选按钮,它会与用户选择的答案更新问题模式。

当用户点击提交,您只需查找每个问题和检索答案选择的用户。

它还解耦从UI使它更容易处理的模式。有了这样的想法,你实际上可以检查是否所有的问题都被回答的例子。这也可以通过添加一些像是的ChangeListener 到模型完成

更新了基本的例子

这是唯一的旨在演示问题的概念举例作为集中控制器/型号

其中,根据屏幕上的射门高出,输出...


香蕉的颜色?
          你的回答是:黄色
    正确的答案是:黄色
                  你是对的
生活的utimate问题宇宙的每一件事情?
          你的回答是:Choclate
    正确的答案是:42
                  你错了
你爸爸是谁?
          你的回答是:R2D2
    正确的答案是:达斯Vadar
                  你错了

 进口java.awt.BorderLayout中;
进口java.awt.EventQueue中;
进口java.awt.GridBagConstraints中;
进口java.awt.GridBagLayout中;
进口java.awt.event.ActionEvent中;
进口java.awt.event.ActionListener;
进口的java.util.ArrayList;
进口java.util.Arrays中;
进口java.util.Collections中;
进口的java.util.List;
进口javax.swing.AbstractAction中;
进口javax.swing.ButtonGroup;
进口javax.swing.JButton中;
进口javax.swing.JFrame中;
进口javax.swing.JPanel中;
进口javax.swing.JRadioButton;
进口javax.swing.UIManager中;
进口javax.swing.UnsupportedLookAndFeelException;
进口javax.swing.border.TitledBorder中;公共类问题答案{    公共静态无效的主要(字串[] args){
        新的问题答案();
    }    公共问题答案(){
        EventQueue.invokeLater(新的Runnable(){
            @覆盖
            公共无效的run(){
                尝试{
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                }赶上(ClassNotFoundException的| InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException前){
                }                JFrame的帧=新的JFrame(测试);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(新的BorderLayout());
                frame.add(新QuestionsPane());
                frame.pack();
                frame.setLocationRelativeTo(NULL);
                frame.setVisible(真);
            }
        });
    }    公共类QuestionsPane继承JPanel {        公共QuestionsPane(){            的setLayout(新的GridBagLayout());
            GridBagConstraints的GBC =新的GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;            最终名单&LT;问题&GT;问题=新的ArrayList&LT;&GT;(3);
            questions.add(新课题(香蕉的颜色?
                            新答(黄色),
                            新答(红粉),
                            新的应答(蓝),
                            新答(橙色)
                    ));
            questions.add(新课题(生命的utimate问题宇宙的每一件事情?
                            新答(42),
                            新答(睡眠),
                            新答(Choclate),
                            新答(1024),
                            新答(微软),
                            新答(苹果)
                    ));
            questions.add(新问题(谁是你爸爸?
                            新答(达斯Vadar),
                            新答(Anikin天行者),
                            新答(尤达),
                            新答(锤的Windo),
                            新答(楚巴卡),
                            新答(R2D2)
                    ));            对(问题问:题){                添加(新QuestionAnswerPane(Q),GBC);            }            gbc.weighty = 1;
            添加(新JPanel(),GBC);
            gbc.weighty = 0;
            gbc.fill = GridBagConstraints.NONE;
            gbc.anchor = GridBagConstraints.CENTER;            JButton的提交=新的JButton(提交);
            submit.addActionListener(新的ActionListener(){
                @覆盖
                公共无效的actionPerformed(ActionEvent的五){
                    对(问题问:题){
                        的System.out.println(q.getText());
                        的System.out.println(\\ t您的回答是:+ q.getSelectedAnswer());
                        的System.out.println(\\里边反正确的答案是:+ q.getCorrectAnswer());
                        的System.out.println(\\ t您的位置:+(q.isCorrectAnswer()右:错误));
                    }
                }
            });            添加(提交,GBC);        }    }    公共类QuestionAnswerPane继承JPanel {        公共QuestionAnswerPane(问问题){            清单&LT;应答和GT;答案=新的ArrayList&LT;&GT;(question.getWrongAnswers());
            answers.add(question.getCorrectAnswer());            Collections.shuffle(答案);            setBorder(新的TitledBorder(question.getText()));
            的setLayout(新的GridBagLayout());
            GridBagConstraints的GBC =新的GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.anchor = GridBagConstraints.WEST;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;            ButtonGroup的BG =新的ButtonGroup();
            对于(答案答案:答案){                一个JRadioButton RB =新一个JRadioButton(新AnswerAction(问题的答案));
                bg.add(RB);
                加(RB,GBC);            }
            gbc.weighty = 1;
            添加(新JPanel(),GBC);        }    }    公共类AnswerAction扩展AbstractAction {        私人最后一个问题的问题;
        私人最终答案的答案;        公共AnswerAction(问问题时,回答的答案){
            this.question =问题;
            this.answer =答案;
            putValue(NAME,answer.getText());
        }        公开回答的getAnswer(){
            返回的答案;
        }        公众质疑getQuestion(){
            返回的问题;
        }        @覆盖
        公共无效的actionPerformed(ActionEvent的五){
            getQuestion()setSelectedAnswer(答案)。
        }    }    公共类问题{        私人答correctAnswer;
        私人列表&LT;应答和GT; wrongAnswers;
        私人答selectedAnswer;        私人字符串文本;        公众质疑(字符串文本,回答正确时,回答错了...){
            wrongAnswers =新的ArrayList&LT;&GT;(Arrays.asList(错误));
            correctAnswer =正确的;
            this.text =文本;
        }        公共字符串的getText(){
            返回文本;
        }        公共答getCorrectAnswer(){
            返回correctAnswer;
        }        公开名单&LT;应答和GT; getWrongAnswers(){
            返回Collections.unmodifiableList(wrongAnswers);
        }        公共答getSelectedAnswer(){
            返回selectedAnswer;
        }        公共无效setSelectedAnswer(答案selectedAnswer){
            this.selectedAnswer = selectedAnswer;
        }        公共布尔isCorrectAnswer(){
            答案answer = getSelectedAnswer();
            回答正确= getCorrectAnswer();
            返回correct.equals(答案);
        }        @覆盖
        公共字符串的toString(){
            返回的getText();
        }    }    公共类答案{        私人字符串文本;        公共答(字符串文本){
            this.text =文本;
        }        公共字符串的getText(){
            返回文本;
        }        @覆盖
        公共字符串的toString(){
            返回的getText();
        }    }}

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();
    }
}

解决方案

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

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();
        }

    }

}

这篇关于得到摆动选定的单选按钮列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆