JLabel Example Multiline Text Java Swing

One of the important features of JLabel is it can be displayed as multiple lines of text with bullets, a very contrast of AWT Label which gives only one line of text. We use HTML here.

Following code on JLabel Example explains.

import javax.swing.* ;
import java.awt.*;  		
import java.awt.event.*;  	

public class JLabelDemo3 extends JFrame
{
  public JLabelDemo3( )
  {
    Container c = getContentPane( );
    c.setLayout(new GridLayout( 4, 1, 0, 10)); 			
    					         // a text of mixed colors
    JLabel lab1 = new JLabel( "  Hello   World  ");
    c.add(lab1) ;
					        // a text of mixed colors with border
    JLabel lab2 = new JLabel( "  Hello   World ");
    lab2.setBorder(BorderFactory.createTitledBorder("Beautiful Colors"));
    c.add(lab2);
					        // a text of mixed fonts with border
    JLabel lab3 = new JLabel( " Hyderabad,  India", SwingConstants.CENTER) ;
    lab3.setFont(new Font("Monospaced", Font.PLAIN, 8)); 
    lab3.setBorder(BorderFactory.createTitledBorder("Attractive Fonts"));
    c.add(lab3);
	 	                                // a text of many lines with border. Make this in a separate file 
		                                //  as the frame height is not enough and keep border layout to container
    String places = " " +
	            "Hyderabad, India:

Tourist places:" + "

    " + "
  • Charminar
  • " + "
  • Salarujung Museum
  • " + "
  • Ramoji Film City
  • " + "
"; JLabel lab4 = new JLabel(places); lab4.setBorder(BorderFactory.createTitledBorder("Multi-Line HTML")); c.add(lab4); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // to close the JFrame setTitle("Multi line Text"); setSize(400,600); setVisible(true); } public static void main(String args[]) { new JLabelDemo3( ); } }


JLabel Example
Output screen on JLabel Example

lab4.setBorder(BorderFactory.createTitledBorder(“Multi-Line HTML”));

With BorderFactory, different types of borders can be given to Swing components. The borders include:

createTitledBorder, createEtchedBorder, createBevelBorder, createRaisedBevelBorder, createLoweredBevelBorder, createLineBorder, createMatteBorder, createCompoundBorder and createEmptyBorder etc.

JLabel Example

Leave a Comment

Your email address will not be published.