我有 20 个单选按钮,它们充当单独的 parking 位。我需要根据可用性启用或禁用。通常,我将它们声明为
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 返回一组本来要禁用的单选按钮,但它们以字符串形式返回。返回的字符串变量是作为对象名称的名称(在本例中为oneA101)。但是,我无法使用字符串变量来禁用单选按钮。如何使用字符串变量来作用于具有相同对象名称的单选按钮?
最佳答案
将其放入 map 中,然后您可以通过名称(或您想要的任何其他字符串...)访问它们
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的生命周期,如果使用不当可能会导致问题!)
关于java - 在 GWT 中使用字符串变量作为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19124107/