-1

I'm reading a string from an xml file and stumbled across two problems. First the string dosen't containt html < br> for line breaking, so the JLabel is just one line. Second I'd like to make the JLabel fit in height according to the "size" of the text. below I sat the height of the JLabel to 200px, but if e.g there's just one word, the JLabel vertically and horizontally centers the text.

Am I missing some "easier" way to do this?

String text = "some long string";

JLabel jltxt = new JLabel(text);
jltxt.setBounds(207, 5, 200, 200);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
PushALU
  • 257
  • 1
  • 3
  • 15
  • *"First the string dosen't containt html < br> for line breaking, so the JLabel is just one line"* That's not a question. Do you **have** a question, and if so, what is it? *"Second I'd like.."* And this is a Q&A site, not a help desk. Each question thread should deal with one question. Start another thread for the other one. And don't forget to *ask a question.* BTW - Java GUIs .. – Andrew Thompson Dec 22 '15 at 01:41
  • .. Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Dec 22 '15 at 01:41
  • For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). Hard code some 'XML' (as it might appear in the input file) in a `String` .. – Andrew Thompson Dec 22 '15 at 01:46
  • Equally, you could also us a `JTextArea` set to auto line/word wrap and make it non-editable and non-focusable – MadProgrammer Dec 22 '15 at 01:55

1 Answers1

0

Instead of setBounds(207, 5, 200, 200); use setPreferredSize(new Dimension(200, 200)); and try the code below

String text = "some long string";

JLabel jltxt = new JLabel(text);
//jltxt.setBounds(207, 5, 200, 200);
jltxt.setPreferredSize(new Dimension(200, 200));
jltxt.setVerticalAlignment(SwingConstants.TOP);
jltxt.setHorizontalAlignment(SwingConstants.LEFT);

Note: For line wrap use html tang in your text

Bahramdun Adil
  • 5,907
  • 7
  • 35
  • 68