3

How do you make the text on a JButton multiline? I have read that most use HTML, but what happens when it is dynamic and you don't know the size of the lines, or what the lines are?

Right now the text on my button just ends with ... as opposed to making a new line.

Most other methods assume you know the string and are hard coded, so you can't do this on the fly.

Edited: I created a method that will do this dynamically for a button

William Falcon
  • 9,426
  • 11
  • 59
  • 106
  • Possible duplicate of [Word Wrap in JButtons](http://stackoverflow.com/questions/5766175/word-wrap-in-jbuttons) or [this answer](http://stackoverflow.com/questions/7861724/is-there-some-word-wrap-property-of-jlabel-exist/7861833#7861833). – Andrew Thompson Apr 01 '13 at 23:46
  • 1
    Answer didn't solve my question, so I added an answer here. http://stackoverflow.com/questions/15770776/how-to-split-a-jbutton-java-text-into-multiple-lines-without-knowing-the-line?noredirect=1#comment22417716_15770776 – William Falcon Apr 02 '13 at 17:57

1 Answers1

17

You'll need to at least know how each line is delimited. For example if lines are delimited with newline characters, you could do:

String twoLines = "Two\nLines";
JButton b = 
    new JButton("<html>" + twoLines.replaceAll("\\n", "<br>") + "</html>");
Reimeus
  • 152,723
  • 12
  • 195
  • 261
  • That only works when the long text already contains information re. line breaks. Using CSS to style the raw text (see links above) is more robust and versatile. – Andrew Thompson Apr 01 '13 at 23:49