Search This Blog

How to Display Multiple Lines in JLabel

multiple lines of text i JLabel, Java source code. Java code to display multiple lines in JLabel. HTML formatting in JLabel Java.
HTML formatted multiline JLabel
Jlabel is actually intended to show single line of text. But you may sometimes ask how to make JLabel to display multiline text. It is possible for JLabel to show multiple lines of text. JLabel in Java can show HTML formatted text. This ability of JLabel can be used to extend longer text onto next line. The following lines of code is an answer for the questions like 'is there a multi-line JLabel' or 'how to display multiple lines using JLabel. Simply, look at the sample code:
JLabel lbl_Multiline=new JLabel();
lbl_Multiline.setText("<html>This is my long text to display with JLabel....</html>");
The JLabel object will display the text in multiple lines if required. If the text is long enough to exceed the width of JLabel, the rest of the text will be displayed in next line automatically. If you want to explicitly place a part of text in a new line, you may use <br/> tag also. 

lbl_Multiline.setText("<html>This is my first line.<br/>This is second line</html>");
Although JLabel is not a multi-line text area, it can be used to display html formatted codes. You can also use some other html tags also to format the JLabel text which will override the foreground color, and formatting of the text set in java code. You can set font size, font color etc in JLabel just using HTML formatting. If you want show only a part of text in bold, you can do it using HTML.

lbl_Multiline.setText("<html><font size=\"6\">my Formatted text</font></html>");
\" is the escape sequence used instead of ". You cannot use " inside a string literal. Therefore, we use \" instead.


No comments:

Post a Comment