3

I have a JButton that I would like to fill in with text that would spread in two lines, however, when I type in the test and use "\n" or "\r" I still get the text on one line.

This is the case with the elements of my jList as well.

Thanks

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Sam
  • 2,702
  • 5
  • 31
  • 45
  • how about "\n\r", that usually works for me – Rob Oct 14 '11 at 14:00
  • 3
    BTW 1) What is a `jField`? A `JTextField` will ignore new lines using either technique shown here. 2) Never use `\n` or `\r`, instead use `System.getProperty("line.seperator")`. – Andrew Thompson Oct 14 '11 at 14:29

2 Answers2

8

Use HTML

JButton button = new JButton("<html><body>line 1 <br /> line 2</body></html>");
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • Interesting... Thanks a lot! – Sam Oct 14 '11 at 14:03
  • 2
    1) For a more complex example (which avoids having to calculate where to put the `
    `), see [LabelRenderTest](http://stackoverflow.com/questions/5853879/java-swing-obtain-image-of-jframe/5853992#5853992). 2) See also [How to Use HTML in Swing Components](http://download.oracle.com/javase/tutorial/uiswing/components/html.html) in the Java Tutorial, and especially note what it says about disabled components.
    – Andrew Thompson Oct 14 '11 at 14:25
0

Indeed, JButton admits HTML. However <body> is not really necessary:

JButton button = new JButton("<html> mylabel <br /> mylabel continues on a newline </html>");

[[ taken from New Line \n is not working in JButton.setText("fnord\nfoo") ; ]]

Community
  • 1
  • 1
mariotoss
  • 414
  • 3
  • 7
  • 17