1
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

camickr
  • 321,443
  • 19
  • 166
  • 288
Kent Ong
  • 97
  • 1
  • 7
  • 1
    This question was originally marked as a duplicate of: http://stackoverflow.com/questions/685521/multiline-text-in-jlabel. All the solutions in that posting suggest using HTML. The OP has stated that using a JTextArea works, however the problem is now an alignment issue with BoxLayout. I have reopened the question to address the alignment issue. – camickr Sep 20 '15 at 17:54
  • Hi thanks for the reply, i do not want to use html because all the string are generated from a user input textfield and displayed by the system automatically, so if i were to use html i will need to read the entire string and replace all the new line to
    and add html opening and closing, in which i do not know what is indicating the newline in the textfield.
    – Kent Ong Sep 21 '15 at 02:33

1 Answers1

1

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Hey thx! this fix my issue! I attempted this solution before, but instead of changing the alignment of textArea, i attempted to change the alignment of other component instead as I sees that it was the other component which went out of alignment! Thanks alot! – Kent Ong Sep 21 '15 at 02:42