有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在GWT中使用字符串变量作为对象的java

我有20个单选按钮,作为单独的停车位。我需要根据可用性启用或禁用。通常,我会将它们声明为

   final RadioButton oneA101 = new RadioButton("new name", "New radio button");

以下似乎不起作用:

   String[] allSlotsToDisable={"oneA101","oneB101","oneA102","oneB102"};
    Object[] rb={};

    for(int i=0;i<allSlotsToDisable.length;i++){
        rb[i]=allSlotsToDisable[i];
        ((FocusWidget) rb[i]).setEnabled(false);
    }

DB返回一组要禁用的单选按钮,但它们作为字符串返回。返回的字符串变量是name作为对象名(本例中为oneA101)。但是,我不能使用字符串变量来禁用单选按钮。如何使用字符串变量对具有相同对象名称的单选按钮进行操作


共 (1) 个答案

  1. # 1 楼答案

    把它放到地图上,然后你就可以通过他们的名字(或者任何你想要的字符串…)访问他们了

    private final Map<String,RadioButton> buttonMap = new HashMap<String,RadioButton>();
    

    然后在代码的后面,当创建按钮时:

    final RadioButton oneA101 = new RadioButton("new name", "New radio button");
    buttonMap.put("new name", oneA101);
    

    之后,当你需要解决这些问题时:

    RadioButton buttonToDoStuffWith = buttonMap.get("new name");
    

    在你的例子中

    String[] allSlotsToDisable={"oneA101","oneB101","oneA102","oneB102"};
    
    for(String toDisable:allSlotsToDisable){
        RadioButton button = buttonMap.get(toDisable);
        if(button!=null) {
            button.setEnabled(false);
        }
    }
    

    (当然要注意这个hashmap的生命周期,如果使用不当,可能会导致问题!)