Kent Ong
Kent Ong

Reputation: 53

Java how to preserve newline from String to JLabel?

JLabel newLabel = new JLabel();
String a = b;//b is String from database.

newLabel.setText(a);

I need to generate text pulled from my database which contains multiple line, but when i put them into the label, all of the text became same line. I tried using JTextArea and it works, however, for some reason it messed with all the other component's alignment in a 1 column BoxLayout panel... which I wanted all the content to be aligned to the left. Any help would be much appreciated! thanks

Upvotes: 1

Views: 128

Answers (1)

camickr
camickr

Reputation: 324098

however, for some reason it messed with all the other component's alignment in a 1 column BoxLayout panel

The is related to the setAlignmentX(...) method of each component.

A JLabel uses 0.0f (for left alignment). A JTextArea and JScrollPane use 0.5f (for center alignment).

Using components with different alignments will cause alignment issues when using a BoxLayout.

The solution is to change the alignment of the text area or scroll pane (whichever component you add to the BoxLayout).

So the basic code would be:

JLabel label = new JLabel(...);
JTextArea textArea = new JTextArea(...);
textArea.setAlignmentX(0.0f);
JPanel panel = new BoxLayout(...);
panel.add(label);
panel.add(textArea);

Now both components will be left aligned.

Upvotes: 1

Related Questions