[英]How to Underline a JLabel on MouseEnter
我试图通过使用以下方式更改字体:
jLabel.setFont(new Font("Tahoma",1,20));
但是这里只有4种样式,即Plain,Bold,Italic,Bold + Italic。
我希望它像HTML中的链接一样工作,当我将鼠标指针悬停在JLabel上时,JLabel会带有下划线。
为了澄清(或不:-)我对mKorbel的评论中引入的困惑
切勿突然创建字体:它很可能会与应用程序中的所有其他字体冲突。 取而代之的是,获取默认值(从下面的片段中的组件实例或UIManager中获取,都没有关系)并派生。
对于使用属性的推导(从mKorbel的答案中毫不客气地加固),这就像
JLabel label = new JLabel("some text - WE ARE UNDERLINED");
MouseListener l = new MouseAdapter() {
Font original;
@Override
public void mouseEntered(MouseEvent e) {
original = e.getComponent().getFont();
Map attributes = original.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
e.getComponent().setFont(original.deriveFont(attributes));
}
@Override
public void mouseExited(MouseEvent e) {
e.getComponent().setFont(original);
}
};
label.addMouseListener(l);
JComponent content = new JPanel();
content.add(label);
content.add(new JButton("dummy focus"));
但是请注意:这还不会给您任何超链接功能! 因此,如果您真正想要的是Hyperlink,请考虑使用具有这种功能的成熟组件,例如SwingX项目中的 fi JXHyperlink 。 您可能要运行在其项目主目录上引用的演示。
用于正确的MouseEvent
JLabel#setFont(new Font(attributes));
然后回来
JLabel#setFont(new Font("Serif", Font.BOLD, 16));
包装到invokeLater
,并来自定义
final Map attributes = (new Font("Serif", Font.BOLD, 16)).getAttributes();
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
将此与必需的CSS一起使用,
yourLabel.setText(htmlIfy("<p style='color:#1C66AE;'>Your text here</p>"));
htmlIfy
函数在哪里
private static final String HTML = "<html>";
private static final String HTML_END = "</html>";
public static String htmlIfy(String s) {
return HTML.concat(s).concat(HTML_END);
}
添加文本,例如链接使用
yourLabel.setText(HTMLTagUtil.htmlIfy(HTMLTagUtil
.linkIfy("Your Text Here")));//Forgot Password?
yourLabel.setCursor(new java.awt.Cursor(
java.awt.Cursor.HAND_CURSOR));
linkIfy
函数在哪里
private static final String A_HREF = "<a href=\"";
private static final String HREF_CLOSED = "\">";
private static final String HREF_END = "</a>";
public static String linkIfy(String s) {
return A_HREF.concat(s).concat(HREF_CLOSED).concat(s).concat(HREF_END);
}
if (CheckBox.isSelected()) {
Font font = CheckBox.getFont();
Map attributes = font.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_GRAY);
CheckBox.setFont(font.deriveFont(attributes));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.