Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Make line break (go to new line) while writing text on JPanel

 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have made JApplet and JPanel on it.

In JPanel I have written some text. I have to write it like one string and to define some logic for line break. When text comes to the width of panel, I should make line break and pass next word that can not fit in line to the new line.

I would be very grateful for some help.
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out FontMetrics. You can get an instance through the Graphics object. This allows you to calculate the width any string would need. I'd use a loop for that. In pseudo code:
1) this will prevent you from entering an infinite loop if you have one word that simply is too long. Without it, the same word would be skipped each time and tried to be drawn on the next line, where it won't fit either.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what's the problem in using a JTextArea that takes up all the area of the panel?
then you just set both setLineWrap() and setWrapStyleWord() to true, and it'll do what you want.

you can make it uneditable, and I'm sure it can be made to appear like a JPanel, if need be
 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob: It looks like very good idea, but I do not know how to make some of things mentioned. For example, how to cut off the right-most word from s?

Michael: It sounds easier, I'll try to make it and report for results.

Thank you both very much.
 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have tried to use JTextArea and set options like you said. It works very nice. I have set JTextArea disabled and it looks like panel now since there is no blinking cursor.

Thank you very much again

Greetings!
 
Rob Spoor
Sheriff
Pie
Posts: 20669
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
maja neskovic wrote:Rob: It looks like very good idea, but I do not know how to make some of things mentioned. For example, how to cut off the right-most word from s?

For future reference: start searching from the end for the last occurrence of a space, punctuation mark, etc. Then use String's substring methods.
 
maja neskovic
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK, Rob. Thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic