我需要读取配置文件并将数据(它由键值对组成)放入一些我必须在JFrame中动态创建的textField中。 之后我想修改textFields并再次将更改保存到文件中。
到目前为止我所拥有的:
FileConfiguration fileConfig = new PropertiesConfiguration(new File("xesfile.properties"));
Iterator<String> keys = fileConfig.getKeys();
while (keys.hasNext()) {
String singleKey = keys.next();
//for the case that a key has multiple values
if (fileConfig.getProperty(singleKey).getClass().equals(ArrayList.class)) {
ArrayList<String> blaArray = (ArrayList<String>) fileConfig.getProperty(singleKey);
for (int i = 0; i < blaArray.size(); i++) {
this.keyLabel = new JLabel(this.nameKeyLabel + this.count);
this.entityLabel = new JLabel(this.nameEntityLabel + this.count);
this.keyTextField = new JTextField();
this.keyTextField.setName(this.nameKeyTextField + this.count);
this.keyTextField.setText(singleKey);
this.entityTextField = new JTextField();
this.entityTextField.setName(this.nameEntityTextField + this.count);
this.entityTextField.setText(blaArray.get(i));
this.count++;
this.configFrame.add(this.keyLabel);
this.configFrame.add(this.keyTextField);
this.configFrame.add(this.entityLabel);
this.configFrame.add(this.entityTextField);
this.configFrame.revalidate();
this.configFrame.repaint();
this.configFrame.pack();
}
//for the case a key has a single value
} else {
this.keyLabel = new JLabel(this.nameKeyLabel + this.count);
this.entityLabel = new JLabel(this.nameEntityLabel + this.count);
this.keyTextField = new JTextField();
this.keyTextField.setName(this.nameKeyTextField + this.count);
this.keyTextField.setText(singleKey);
this.entityTextField = new JTextField();
this.entityTextField.setName(this.nameEntityTextField + this.count);
this.entityTextField.setText((String) fileConfig.getProperty(singleKey));
this.count++;
this.configFrame.add(this.keyLabel);
this.configFrame.add(this.keyTextField);
this.configFrame.add(this.entityLabel);
this.configFrame.add(this.entityTextField);
this.configFrame.revalidate();
this.configFrame.repaint();
this.configFrame.pack();
}
}
如您所见,在while循环的每次传递中都会反复创建TextField。但是我需要访问我在循环的第一遍中为示例创建的textFields。
如果我将getName()
访问TextFields,我们会被退回,但事实并非如此。
任何人都可以帮助我吗?
答案 0 :(得分:1)
将TextField存储在Map中,其中键作为名称,值为TextField对象本身。您可以稍后使用以下方式访问它:
TextField textField = map.get("myField");
答案 1 :(得分:1)
这很简单
// In loop
1) Create the component.
2) Add it to an Generic ArrayList
3) You can also attach an actionListener to the component in loop if you want.
// Out of loop
4) Iterate the ArrayList and access the desire component.