如何使用JavaFX反复格式化带有逗号分隔符的标签[复制]

问题描述 投票:0回答:1

这个问题在这里已有答案:

所以基本上我想做以下事情:

   String s1 = "hello";

   for(int count = s1.length() -1; count >= 0; count--){
        System.out.printf("%c, ", s1.charAt(count));
    }

但是在标签中这样做。如何格式化printf等标签?使用setTextf并不像下面所示:

String s1 = "hello";
for(int count = s1.length() -1; count >= 0; count--){
        label1.setTextf("%c, ", s1.charAt(count));
    }
javafx formatting label settext
1个回答
2
投票

printf()方法专门用于将格式化的String打印到输出控制台。

如果要将String格式化为其他目的,则需要使用String.format()方法:

String s1 = "hello";
for(int count = s1.length() -1; count >= 0; count--){
    label1.setText(String.format("%c, ", s1.charAt(count)));
}

但是,在你尝试做的循环中执行此操作将导致单个char作为最终的Label文本,因为每次调用setText()都将覆盖前一个。

相反,你应该使用String构建你的最终StringBuilder

String s1 = "hello";
StringBuilder sb = new StringBuilder();

for(int count = s1.length() -1; count >= 0; count--){
    sb.append(String.format("%c, ", s1.charAt(count)));
}

label1.setText(sb.toString());
© www.soinside.com 2019 - 2024. All rights reserved.