删除动态jTextFields的最后一个逗号

时间:2022-02-28 22:31:21

I am getting value of dynamically added JTextField using this code:

我正在使用以下代码获得动态添加的JTextField的价值:

EDITED:

    Component[] children = jPanel1.getComponents();
// iterate over all subPanels...
for (Component sp : children) {
    if (sp instanceof subPanel) {
        Component[] spChildren = ((subPanel)sp).getComponents();
        // now iterate over all JTextFields...
        for (Component spChild : spChildren) {
            if (spChild instanceof JTextField) {
                String text = ((JTextField)spChild).getText();
                System.out.println(text);
            }
        }
    }
}

Output text file I got: text1,text2,text3,

我得到的输出文本文件:text1,text2,text3,

Now appeared next problem - "last comma". I found that Guava can solve the problem, but due to less experience I couldn't implement. If possible could you give me some advice or suggestion.

现在出现了下一个问题 - “最后一个逗号”。我发现Guava可以解决问题,但由于经验不足,我无法实现。如果可能的话,你可以给我一些建议或建议。

Thank you in advance.

先感谢您。

2 个解决方案

#1


Use a StringJoiner:

使用StringJoiner:

StringJoiner joiner=new StringJoiner(",");
for (Component spChild : spChildren) {                     
    if (spChild instanceof JTextField) {
        String text = ((JTextField)spChild).getText();
        joiner.add(text);
    }
}
outfile.write(joiner.toString());

#2


I am not sure if your spChildren is a List or an Array, my assumption it's List, therefore spChildren.size() is used, in case its and Array spChildren.length will replace it.

我不确定你的spChildren是List还是一个数组,我的假设是List,因此使用spChildren.size(),以防它和Array spChildren.length取代它。

for (int i = 0; i < spChildren.size(); i++) {                     
     if (spChildren.get(i) instanceof JTextField) {
         String text = ((JTextField)spChildren.get(i)).getText();
         if (i == (spChildren.size() - 1)) {
             outfile.write(text);
         } else {
             outfile.write(text + "," );
         }
     }
}

#1


Use a StringJoiner:

使用StringJoiner:

StringJoiner joiner=new StringJoiner(",");
for (Component spChild : spChildren) {                     
    if (spChild instanceof JTextField) {
        String text = ((JTextField)spChild).getText();
        joiner.add(text);
    }
}
outfile.write(joiner.toString());

#2


I am not sure if your spChildren is a List or an Array, my assumption it's List, therefore spChildren.size() is used, in case its and Array spChildren.length will replace it.

我不确定你的spChildren是List还是一个数组,我的假设是List,因此使用spChildren.size(),以防它和Array spChildren.length取代它。

for (int i = 0; i < spChildren.size(); i++) {                     
     if (spChildren.get(i) instanceof JTextField) {
         String text = ((JTextField)spChildren.get(i)).getText();
         if (i == (spChildren.size() - 1)) {
             outfile.write(text);
         } else {
             outfile.write(text + "," );
         }
     }
}