JavaUser Code: Giving JLabel a Different Face

User Code: Giving JLabel a Different Face

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) {
          super();
          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));
                  else
                      g.setFont(new java.awt.Font("Dialog", 0, 12));
              }
          else {
              if(i < nPos)
                  g.setFont(new java.awt.Font("Dialog", 0, 12));
              else
                  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;
      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(':',
  MultiFontLableUI.BOLD_FIRST)); 
  frm.getContentPane().add(lbl);
  frm.setVisible(true);         
  }
  
  
  }

This code was contributed by Ramkumar Venkatesan.

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

Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.
Get the Free Newsletter!
Subscribe to Developer Insider for top news, trends & analysis
This email address is invalid.

Latest Posts

Related Stories