如何在核心java程序中添加单选按钮组,以便一次只选择一个单选按钮?

我正在核心java中构建一个项目。 我坚持制作一个单选按钮组(用于输入性别(男/女)。为此我需要一个无线电组,以便一次只选择一个单选按钮;并相应地将输入输入数据库。请帮忙。

请尝试使用ButtonGroup组件并将两个名为male和female的JRadioButton组件添加到ButtonGroup对象中,然后使用setVisible(true)将其显示在JFrame中; 方法。

下面的代码应该是有用的: –

import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JRadioButton; public class Rb extends JFrame { Rb (){ JRadioButton male = new JRadioButton("male"); JRadioButton female = new JRadioButton("Female"); ButtonGroup bG = new ButtonGroup(); bG.add(male); bG.add(female); this.setSize(100,200); this.setLayout( new FlowLayout()); this.add(male); this.add(female); male.setSelected(true); this.setVisible(true); } public static void main(String args[]){ Rb j = new Rb(); } 

}

这是一个单选按钮分组:

 JRadioButton button1 = ...; button1.setSelected(true); JRadioButton button2 = ...; ButtonGroup group = new ButtonGroup(); group.add(button1); group.add(button2); 
  JPanel radioButtonPanel = new JPanel(); append = new JRadioButton("append"); build = new JRadioButton("xx1"); build.setSelected(true); //sets this button as selected on startup small = new JRadioButton("x.1.x"); huge = new JRadioButton("1.xx"); // Create the button group to keep only one selected. ButtonGroup btnGroup = new ButtonGroup(); btnGroup.add(append); btnGroup.add(build); btnGroup.add(small); btnGroup.add(huge); 

然后将按钮添加到JPanel或类似的东西。