Search code examples
javafxformattinglabelsettext

How to format a label with a comma delimiter in reverse using JavaFX


So basically I want to do the following:

   String s1 = "hello";

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

but do that in a label instead. How can I format a label like printf? Using setTextf does not woek as seen below:

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

Solution

  • The printf() method is intended specifically for printing a formatted String to your output console.

    If you want to format a String for other purposes, you need to use the String.format() method:

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

    However, doing this within a loop as you are trying to do will result in a single char as your final Label text, since each call to setText() will overwrite the previous one.

    Instead, you should build your final String using a 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());