JavaUser Code: Giving JLabel a Different Face

User Code: Giving JLabel a Different Face content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

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]

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories