Search code examples
javaswingwhitespacejlabel

How can I get my JLabel to draw a space in java


I want my JLabel to draw spaces but for some reason they don't get drawn. This is an example of something that the JLabel should draw, but it doesn't do so for some reason:

                 =========                    
                 ==========                   
                 ==========                   
                 ==========                  

                 =========                    
                  =======                     
                              

Is there a way for it to do so? Not with borders but with <html> or \n or something else.
The code for the JLabel text:

label.setText("<html>");
for (int i = 0; i < image.getHeight(); i++) {
    for (int j = 0; j < image.getWidth(); j++) {
        char symbol = getSymbol(i,j,image);
        line += symbol;
        if (line.length() >= image.getWidth()) {
            label.setText(label.getText()+""+line+"<br>");
            line = "";
        } // end of if
        System.out.print(symbol);
    }
    System.out.println();
}
label.setText(label.getText()+"<br></html>"); 

Solution

  • Let's assume you want to draw the following:

      x
     x
    x
    

    In plain HTML you can add &nbsp;-encoded spaces (non breaking spaces) or use preformatted text.

    Example using encoded spaces:

    String txt = "&nbsp;&nbsp;x<br>&nbsp;x<br>x";
    JLabel label = new JLabel("<html>" + txt + "</html>");
    

    Example using preformatted text:

    String txt = "  x\n x\nx";
    JLabel label = new JLabel("<html><pre>" + txt + "</pre></html>");