【发布时间】:2014-04-30 01:08:53
【问题描述】:
使用 CodenameOne,我根据数据库表上的记录数创建了一个 RadioButtons 数组。
Container searchDisplayContainer = findMyContainer(f);
for(int i=0; i < records.length; i++) {
RadioButton rdb = new RadioButton();
rdb.setName("rdb"+i);
rdb.setText("rdb"+i);
rdb.setGroup("locations");
searchDisplayContainer.addComponent(rdb);
}
使用此代码,模拟器屏幕上会显示一些 RadioButton。
我的问题是显示单选按钮后,我无法检查选择了哪个。
通常我可以在theme.res中创建单选按钮并在代码中调用它:
RadioButton rdb1 = findRadioButton(f);
并检查是否使用 if(rdb1.isSelected) 选择了按钮
但是,由于我最初并未在 theme.res 中创建单选按钮,因此无法使用 findRadioButton(f) 方法。
我的问题是如何在代码中创建多个 RadioButtons,然后在按下提交按钮后检查它们是否被选中?
问题修改
package userclasses;
import generated.StateMachineBase;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.ui.util.Resources;
/**
*
* @author Your name here
*/
public class StateMachine extends StateMachineBase {
private Container searchDisplayContainer;
private final int recordLength = 5;
private ButtonGroup bg = new ButtonGroup();
private RadioButton[] rdbs = new RadioButton[recordLength];
public StateMachine(String resFile) {
super(resFile);
}
/**
* this method should be used to initialize variables instead of
* the constructor/class scope to avoid race conditions
*/
protected void initVars(Resources res) {
}
@Override
protected void beforeMain(Form f) {
searchDisplayContainer = findContainer1(f);
for(int i=0;i<recordLength;i++){
rdbs[i].setName("rdb"+i);
rdbs[i].setText("rdb"+i);
//add to button group
bg.add(rdbs[i]);
//add to container
searchDisplayContainer.addComponent(rdbs[i]);
}
}
@Override
protected void onMain_ButtonAction(Component c, ActionEvent event) {
System.out.println(bg.getSelectedIndex());
}
}
【问题讨论】:
标签: java radio-button components codenameone