[英]How to add a radio button group in a core java program such that only one radio button is selected at one time?
我正在核心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("x.x.1");
build.setSelected(true); //sets this button as selected on startup
small = new JRadioButton("x.1.x");
huge = new JRadioButton("1.x.x");
// 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或類似的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.