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.]
0 Comments (click to add your comment)
Networking Solutions



Solid state disks (SSDs) made a splash in consumer technology, and now the technology has its eyes on the enterprise storage market. Download this eBook to see what SSDs can do for your infrastructure and review the pros and cons of this potentially game-changing storage technology.