如何在Eclipse(JSwing)中验证JRadioButton?

时间:2016-12-12 13:32:38

标签: java swing

我正在做一个测验程序,因此我需要JRadioButton。但是,问题是我不知道如何验证它们,只能选择一个单选按钮。

public class QuizQ1Panel extends MasterPanel{

    protected static final JFrame JFrame = null;

    /**
     * Create the panel.
     * @param myPanel 
     */
    public QuizQ1Panel(JFrame mf) {
        super(mf);

        setBounds(100, 100, 900, 750);

        JLabel lblQuiz1JY = new JLabel("This quiz consists of 5 questions.");
        lblQuiz1JY.setFont(new Font("Tahoma", Font.BOLD, 16));
        lblQuiz1JY.setBounds(470, 162, 429, 20);
        add(lblQuiz1JY);

        JLabel lblQ1JY = new JLabel("Question 1");
        lblQ1JY.setFont(new Font("Tahoma", Font.BOLD, 17));
        lblQ1JY.setBounds(66, 216, 120, 20);
        add(lblQ1JY);

        JLabel lblQns1JY = new JLabel("What shape is used to represent a 'process' symbol?");
        lblQns1JY.setFont(new Font("Tahoma", Font.BOLD, 17));
        lblQns1JY.setBounds(66, 241, 534, 20);
        add(lblQns1JY);
         /* How do I validate JRadioButtons such that only one button can be selected?*/
        JRadioButton rdbtnRectJY = new JRadioButton("A. Rectangle");
        rdbtnRectJY.setBounds(60, 273, 155, 29);
        add(rdbtnRectJY);



        JRadioButton rdbtnDiaJY = new JRadioButton("B. Diamond");
        rdbtnDiaJY.setBounds(60, 310, 155, 29);
        add(rdbtnDiaJY);

        JRadioButton rdbtnCirJY = new JRadioButton("C. Circle");
        rdbtnCirJY.setBounds(60, 344, 155, 29);
        add(rdbtnCirJY);

        JRadioButton rdbtnParaJY = new JRadioButton("D. Parallelogram");
        rdbtnParaJY.setBounds(60, 381, 155, 29);
        add(rdbtnParaJY);

        /* Currently when I clicked on JRadioButton, all can be selectd. However, I only want one button to be selected. So, how should I validate it? */

1 个答案:

答案 0 :(得分:1)

如评论中所述,使用Buttongroups完成该任务。它们一次只允许选择1个RadionButton:https://docs.oracle.com/javase/7/docs/api/javax/swing/ButtonGroup.html

致@LukasRotter