Java RadioButton组的一些应用例子

初学GUI对RadionButton组的选定RadioButton的获取找了几个方法:

一:用循环把按钮添加到组内,找选取值时再用一个循环。

//创建单选按钮组
private JRadioButton rb[];
String[] sex = {"male","female"};
ButtonGroup bg = new ButtonGroup();
rb = new JRadioButton[sex.length]
for(int i=0; i < sex.length; i++){
     rb[i] = new JRadioButton(sex[i]);
     bg.add(rb[i]);
}
//获取选取值
for(int i=0;i<rb.length;i++){
     String str = "";
     if(rb[i].isSelected())
         str += rb[i].getText();
}

——这个方法来自《Java面向对象程序设计基础教程》


二:写一个RadioButtonList类,再提供getResults()方法来获取值


import javax.swing.*;

public class RadioButtonList extends JPanel{
	
	String[] items = null;
	JRadioButton[] jrbs = null;
	
	public RadioButtonList(String[] items){
		
		this.items = items;
		ButtonGroup bg = new ButtonGroup();
		
		jrbs = new JRadioButton[items.length];
		for(int i = 0; i < jrbs.length;i++){
			jrbs[i] = new JRadioButton(this.items[i]);
			add(jrbs[i]);
			bg.add(jrbs[i]);
		}
	}
	
	public String getResults(){
		String results = "";
		
		for(JRadioButton jrb : jrbs){
			if(jrb.isSelected()){
				results = jrb.getText();
				break;
			}
		}
		return results;
	}
}

——这个方法来自《Java通用范例开发金典》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 JavaFX 应用程序,它使用 RadioButton 控件来允许用户选择不同的选项: ```java import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class RadioButtonDemo extends Application { @Override public void start(Stage stage) { // 创建一个垂直布局 VBox vbox = new VBox(); vbox.setPadding(new Insets(10, 50, 50, 50)); vbox.setSpacing(10); // 创建一个标签 Label label = new Label("请选择您最喜欢的编程语言:"); // 创建一个单选按钮 ToggleGroup group = new ToggleGroup(); // 创建三个单选按钮 RadioButton radioButton1 = new RadioButton("Java"); radioButton1.setToggleGroup(group); radioButton1.setSelected(true); RadioButton radioButton2 = new RadioButton("Python"); radioButton2.setToggleGroup(group); RadioButton radioButton3 = new RadioButton("C++"); radioButton3.setToggleGroup(group); // 将单选按钮和标签添加到布局中 vbox.getChildren().addAll(label, radioButton1, radioButton2, radioButton3); // 创建一个场景并将其添加到舞台 Scene scene = new Scene(vbox, 400, 250); stage.setScene(scene); stage.setTitle("RadioButton Demo"); stage.show(); } public static void main(String[] args) { launch(args); } } ``` 该代码创建一个垂直布局,并向其中添加一个标签和三个单选按钮。默认情况下,第一个单选按钮(Java)被选中。当用户选择不同的单选按钮时,选中的按钮将被突出显示。 请注意,我们使用 `ToggleGroup` 类来确保一次只能选择一个单选按钮。在代码中,我们将三个单选按钮添加到同一中,以便只能选择其中一个。我们还使用 `setSelected(true)` 方法将第一个单选按钮设置为默认选中状态。 希望这个例子能够帮助你理解 RadioButton 控件在 JavaFX 应用程序中的使用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值