简体   繁体   English

Java/Swing 将输入从多个 JTextField 保存到文件中

[英]Java/Swing Save input to a file from multiple JTextField

i'm trying to code a frame that get from the user a bunch of parameters and save them into a csv file and then redirect to a new frame that run a simulation, the problem is used a for loop to generate easily the text fields however i don't know how to write the event listener that retrive the data from all the text fields,here's the code:我正在尝试编写一个框架,该框架从用户那里获取一堆参数并将它们保存到 csv 文件中,然后重定向到运行模拟的新框架,但问题是使用 for 循环轻松生成文本字段我不知道如何编写从所有文本字段中检索数据的事件侦听器,代码如下:

       private void ZoneTexte(String texte,JPanel pan) {
       JLabel label=new JLabel();
       label.setText(texte);
       JTextField text = new JTextField(20);
       pan.add(label);
       pan.add(text);
   }
   /**
    * 
    */
   private void SaveParam() {
       String [] param= {"Nom Milieu","ProbaRoche","ProbaHerbe","Qherbe","DistCaractHerbe","FacteurHerbe","RayonLac","ProfondeurMaxLac","SigmaLac"};
       JLabel label=new JLabel();
       label.setText("Définir vos propres paramètres de simulation:");
       EditPanel.add(label);
       for(String s:param) {
           JPanel pan1= new JPanel();
           ZoneTexte(s+" :",pan1);
           EditPanel.add(pan1);
       }
       JButton save=new JButton();
       save.setText("Enregistrer et démarrer la simulation");
       EditPanel.add(save);
       save.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub


        }
           });
   }
   [The file format that i desire is this][1]

Keep the text fields in a list and iterate it when saving.将文本字段保留在列表中,并在保存时对其进行迭代。

 List<JTextField> fieldList = new ArrayList <>() ;

...
    EditPanel.add(pan1)
    fieldList.add(pan1);
}

 save.addActionListener(e -> {
        for (JTextField field : fieldList) {
             file.writeString(field.getText); // however you want to write it 
        } 
 }

IMHO, you need to use a structure like a Map to keep a reference to each TextField.恕我直言,您需要使用像 Map 这样的结构来保持对每个 TextField 的引用。 Then in your listener, you will parse your memory structure so that filling your csv.然后在你的监听器中,你将解析你的 memory 结构,以便填充你的 csv。

// Somewhere in your init class
var fieldsMap = new HashMap<String,TextField>();

// In ZoneTexte method
fieldsMap.put(texte,text);      

// In your listener
var value = mapField.get("ProbaRoche").getText();

Perhaps, use a key unique for the field that can be used in different location of your code.或许,为可以在代码的不同位置使用的字段使用唯一的键。

HTH HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM