lol
lol

Reputation: 1

Java (JLabel spacing)

I want the JLabel to display "hi, my name is Bob"

However, when I coded: JLabel.setText("hi, my name is Bob");

the spaces are "consumed" and the output will read "hi, my name is bob"

Can anyone please help me on this? Thanks in advance

Upvotes: 0

Views: 1149

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168835

Here are two ways that both have the same effect. One sets the font to MONOSPACED while the other marks the text as HTML preformatted (which also uses a monospaced font & preserves spaces and tabs).

String TEXT = "hi,      my name is Bob";
 // ...

JLabel l = new JLabel(TEXT);
l.setFont(new Font(Font.MONOSPACED, Font.PLAIN, l.getFont().getSize()));
ui.add(l);
ui.add(new JLabel("<html><body><pre>" + TEXT));

Having said that, I agree with @Madonah & @maraca that this is best handled in two labels, using layouts (borders and padding) to achieve the required result.

Upvotes: 2

Related Questions