Search code examples
javaswingtextjpanel

JPanel to display large amount of text


I'm currently searching for a method to display an introduction for my program. Every part of the program has it's own instructions that are several lines long. At the end of each line there is \n\n for formatting.

It would be cool if the font size could adjust automatically to the panel size and if the text could be centered. I tried TextLayout and adding the text to a simple JLabel but none of this displays the text correctly.

Any suggestions on how to accomplish this task?


Solution

  • You can also use HTML formatting in the JLabel text. All you need to do is surround the text with <html> and </html>, set the font size with a <font> element, and replace every \n with <br>.

    String formatted = text.replace("\n", "<br>");
    formatted = "<html><font size='9'>" + formatted + "</font></html>";
    JLabel label = new JLabel(formatted);
    

    See How to Use HTML in Swing Components.