gpt4 book ai didi

java - 如何在 Eclipse (Swing) 中验证单选按钮?

转载 作者:行者123 更新时间:2023-12-01 09:07:58 26 4
gpt4 key购买 nike

我正在做一个测验程序,因此我需要 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? */

最佳答案

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

感谢@LukasRotter

关于java - 如何在 Eclipse (Swing) 中验证单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41102064/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com