在swing中获取选定的单选按钮列表

Posted

技术标签:

【中文标题】在swing中获取选定的单选按钮列表【英文标题】:get selected radio button list in swing 【发布时间】:2013-09-10 04:03:18 【问题描述】:

我将使用 java swing 创建多项选择题应用程序。我在单独的 jPanel 中创建了带有单选按钮列表的 swing 类。我需要找到选定的单选按钮并在提交按钮时在正确答案上突出显示。但我无法在摇摆中获得选定的单选按钮列表。谁能给我一个好的解决方案?

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

【问题讨论】:

创建问题的模型,UI 可以创建该模型的视图。允许视图将选定的答案设置回模型... 请问什么逻辑???问题是随机显示的,你之前的选择存储在哪里???仅在 JLabel 中,getCorrectAnswer 是硬编码的??? 我已经在 QuestionPane 类中创建了 QuestionUI,我在这里使用它的对象 如需尽快获得更好的帮助,请发帖SSCCE。 是的,问题和答案是随机显示的,不是,getCorrectAnswer() 是 Question pojo 中的 getter,它存储了正确的答案。我使用单独的 Answer dto 将 true 设置为正确答案并将其存储为 setHideActionText() 【参考方案1】:

创建一个能够引用Question 模型的QuestionAnswerPane

此面板将负责生成由Question 模型表示的视图并将用户的响应存储在其中。

QuestionAnswerPane 应该知道JRadioButton 属于哪个answer。当用户选择其中一个单选按钮时,它将使用用户选择的答案更新Question 模型。

当用户点击Submit 时,您只需查找每个Question 并检索用户选择的答案。

它还将模型与 UI 分离,使其更易于处理。有了这个想法,您实际上可以检查所有问题是否都已得到回答。这也可以通过在模型中添加 ChangeListener 之类的东西来实现

更新了 BASIC 示例

这只是一个示例,旨在展示Question 是集中控制器/模型的概念

根据上面的屏幕截图,输出...

香蕉的颜色? 你的回答是:黄色 正确答案是:黄色 你说的对 生命的终极问题是宇宙和万物? 你的回答是:巧克力 正确答案是:42 您错了 你爸爸是谁? 你的回答是:R2D2 正确答案是:达斯·瓦达 您错了
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();
        

    


【讨论】:

您的意思是使用Question 模型将所有属性设置为QuestionAnswerPane,在迭代QuestionAnswerPane 并显示问题之后?单击提交按钮时,getSelectedValue 出现问题 没有。我的意思是,允许QuestionAnswerPane 将“从用户那里选择答案”设置回Question 模型,那么你就不用关心 UI 处于什么状态了... 我添加了我正在谈论的概念。您应该能够看到 Question 是关键,它包含确定问题所要求的内容和用户选择的内容所需的所有信息,所有这些都不以任何方式依赖 UI...我不关心答案的来源或格式... 感谢您的指导。 我必须用问题显示正确答案,所以你能给我一个小主意,在QuestionPane 中标记正确答案(突出显示单选按钮文本)。主要问题是我无法在 ui 中专门选择提取问题。

以上是关于在swing中获取选定的单选按钮列表的主要内容,如果未能解决你的问题,请参考以下文章

单击提交后如何获取选定的单选按钮以显示特定的隐藏 div?

如何使用js获取选定的单选按钮值

如何使用js获取选定的单选按钮值

Android从选定的单选按钮获取价值

尝试获取选定的单选按钮值时jQuery抛出错误

基于选定的单选按钮在 Tkinter 中启动命令?