【问题标题】:How to create dynamic radiobuttons in CodenameOne如何在 CodenameOne 中创建动态单选按钮
【发布时间】: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


    【解决方案1】:

    您需要创建ButtonGroup 类的实例并向其添加单选按钮,以便将其与组中的其他按钮相关联。

    【讨论】:

    • 嗨 Shai,感谢您的提示,但在发布最初的问题之前,我确实尝试使用 ButtonGroup。我已修改问题以包含测试场景。可以看出,我创建了 ButtonGroup 的一个实例,还创建了 RadioButtons 数组。但是,当我单击提交按钮(onMain_ButtonAction)时。我收到错误“java.lang.reflect.InvocationTargetException”并且模拟器在显示单选按钮之前关闭。我希望能够在单击提交按钮时打印所选单选按钮的索引。请您的见解。谢谢!
    • 你得到一个 NullPointerException 因为你分配了数组并且没有分配其中的元素所以 rdbs[i] 为空。查看堆栈,它实际上也会显示空指针异常并将您指向特定的行。
    猜你喜欢
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2016-01-09
    • 2011-07-28
    • 2021-07-26
    • 2022-01-11
    相关资源
    最近更新 更多