想必每个数据对象都会有些必填项, 因此做了一个标签提示哪个是必填项.
这个也是重写UI的, 不过和M2那个Label一样, 因为Label是透明的, 应该可以应用于各种L&F.
import
java.awt.Color;
import
java.awt.Graphics;
import
javax.swing.JComponent;
import
javax.swing.JLabel;
import
javax.swing.plaf.ComponentUI;
import
javax.swing.plaf.metal.MetalLabelUI;
import
com.sun.java.swing.SwingUtilities2;
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
/** */
/**
* Created at 2006-8-7 9:46:32<br>
* 必填项标签
*
* @author Brad.Wu
* @version 1.0
*/
@SuppressWarnings(
"serial"
)
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
public class RequiredLabel extends JLabel ...
{
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
public RequiredLabel() ...{
}
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
public RequiredLabel(String text) ...{
super("* " + text);
}
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
/** *//**
* (非 Javadoc)
*
* @see javax.swing.JLabel#setText(java.lang.String)
*/
@Override
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
public void setText(String text) ...{
if (text.startsWith("* "))
super.setText(text);
else
super.setText("* " + text);
}
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
/** *//**
* (非 Javadoc)
*
* @see javax.swing.JLabel#updateUI()
*/
@Override
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
public void updateUI() ...{
setUI(new RequiredLabelUI());
}
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
/** *//**
* Created at 2006-8-7 9:53:32<br>
* 必填项标签UI
*
* @author Brad.Wu
* @version 1.0
*/
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
static class RequiredLabelUI extends MetalLabelUI ...{
protected static RequiredLabelUI labelUI = new RequiredLabelUI();
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
public static ComponentUI createUI(JComponent c) ...{
return labelUI;
}
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
/** *//**
* (非 Javadoc)
*
* @see javax.swing.plaf.basic.BasicLabelUI#paintEnabledText(javax.swing.JLabel,
* java.awt.Graphics, java.lang.String, int, int)
*/
@Override
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
protected void paintEnabledText(JLabel l, Graphics g, String s, int textX, int textY) ...{
int mnemIndex = l.getDisplayedMnemonicIndex();
g.setColor(l.getForeground());
int x = l.getFontMetrics(l.getFont()).stringWidth("*");
SwingUtilities2.drawStringUnderlineCharAt(l, g, s.substring(1), mnemIndex, textX + x,
textY);
g.setColor(new Color(255, 100, 100));
SwingUtilities2.drawString(l, g, "*", textX, textY + 2);
}
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)