假设我们有一个复选框:
JCheckBox lang_1 = new JCheckBox("English");
此外,我们还有一个绑定(bind)到 ActionListener 的变量,因此它会在 ActionEvent 发生时发生变化。这是 ActionEvent 中的变量:
(String) abbr = JComboBox<ComboItem> comboBox.getSelectedIndex().toString();
现在,我有 abbr 等于 1 所以我想 lang_1.setEnabled(true);
有什么方法可以将“lang_”与 abbr 混合使用,就像我使用 lang_1 一样?
(在 jQuery 中你可以这样做:$("lang_"+abbr).doSomethingFunction();
)
最佳答案
最简单的方法是将 JCheckBoxes 放在数组列表中并使用它们的索引调用它们:
List<JCheckBox> boxes = new ArrayList<JCheckBox> ();
boxes.add(new JCheckBox("English"));
// populate the list with the other check boxes
String abbr = JComboBox<ComboItem> comboBox.getSelectedIndex().toString();
int index = Integer.parseInt(abbr);
boxes.get(index).setEnabled(true);
您需要在边界、数字解析等方面添加相关的错误处理代码。
关于java - 有没有办法在对象名称中使用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12596180/