How can we implement a JLabel text with different color and font in Java?


JLabel

  • A JLabel class can extend JComponent class and an object of JLabel provides text instructions or information on a GUI.
  • A JLabel can display a single line of read-only text, an image or both text and an image.
  • A JLabel can also display a single line of text with different colors and fonts using <font size='font-size' color='color of the text'> Some Text </font> tag inside a HTML tag.
  • A JLabel can explicitly generate a PropertyChangeListener interface.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MultiColorLabelTest extends JFrame {
   public MultiColorLabelTest() {
      setTitle("MultiColorLabel Test");
      setLayout(new FlowLayout());
      // multi colored with different font size label
      JLabel label = new JLabel("<html><font size='5' color=blue> Welcome to</font> <font            size='6'color=green> Tutorials Point</font></html>");
      add(label);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new MultiColorLabelTest();
   }
}

Output

Updated on: 10-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements