October 19, 2018
Hot Topics:

User Code: Giving JLabel a Different Face

  • June 7, 2001
  • By Ramkumar Venkatesan
  • Send Email »
  • More Articles »

Below is the source code for making a JLabel have two different fonts.

  import javax.swing.*;
  import java.awt.Graphics;
  import javax.swing.plaf.basic.BasicLabelUI;
  import javax.swing.plaf.basic.BasicGraphicsUtils;
  class MultiFontLableUI extends BasicLabelUI {
      public static int BOLD_FIRST = 1;
      public static int BOLD_SECOND = 2;
      private char m_cDivide;
      private int m_nBold;
      public MultiFontLableUI(char cDivide, int nBold) {
          m_cDivide = cDivide;
          m_nBold = nBold;
      protected void paintEnabledText(JLabel l,Graphics g,String s,int
  textX,int textY) {
  int accChar = l.getDisplayedMnemonic();
          int nLen = s.length();
          int nPos = getPosition(s);
          for(int i=0; i < nLen; i++) {
              if(m_nBold==1) {
                  if(i < nPos)
                      g.setFont(new java.awt.Font("Dialog", 1, 12));
                      g.setFont(new java.awt.Font("Dialog", 0, 12));
          else {
              if(i < nPos)
                  g.setFont(new java.awt.Font("Dialog", 0, 12));
                  g.setFont(new java.awt.Font("Dialog", 1, 12));
          BasicGraphicsUtils.drawString(g, String.valueOf(s.charAt(i)),
  accChar, textX, textY);
          textX += g.getFontMetrics().charWidth(s.charAt(i));
      public int getPosition(String strLabel) {
          int i=0;
  int len = strLabel.length();
          if(len==0) return -1;
          while(i<len) {
      if(strLabel.charAt(i)==m_cDivide) return ++i;
    return -1;
  class TestMultiFontLabel {
  public static void main(String [] args) {
  JFrame frm = new JFrame();
  JLabel lbl = new JLabel("Name : Some Name");
          lbl.setUI(new MultiFontLableUI(':',

This code was contributed by Ramkumar Venkatesan.

[To contribute a code article to Gamelan, please contact kmurphy@internet.com.]

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

By submitting your information, you agree that developer.com may send you developer offers via email, phone and text message, as well as email offers about other products and services that developer believes may be of interest to you. developer will process your information in accordance with the Quinstreet Privacy Policy.


Thanks for your registration, follow us on our social networks to keep up-to-date