【发布时间】:2012-09-12 13:20:39
【问题描述】:
我尝试使用以下方法更改字体:
jLabel.setFont(new Font("Tahoma",1,20));
但是这里只有 4 种样式,Plain、Bold、Italic、Bold+Italic。
我希望它像 HTML 中的链接一样工作,当我将鼠标光标悬停在 JLabel 上时,它会带下划线。
【问题讨论】:
标签: java html swing fonts jlabel
我尝试使用以下方法更改字体:
jLabel.setFont(new Font("Tahoma",1,20));
但是这里只有 4 种样式,Plain、Bold、Italic、Bold+Italic。
我希望它像 HTML 中的链接一样工作,当我将鼠标光标悬停在 JLabel 上时,它会带下划线。
【问题讨论】:
标签: java html swing fonts jlabel
澄清(或不澄清 :-) 我的 cmets 对 mKorbel 引入的混淆
永远不要突然创建字体:它很可能会与应用程序中的所有其他字体发生冲突。取而代之的是,获取默认值(从下面显示的 sn-p 或 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"));
但请注意:这还不会为您提供任何超链接功能!因此,如果超链接是您真正所追求的,请考虑使用具有此类功能的成熟组件,例如 f.i. JXHyperlink in the SwingX project。您可能希望运行其项目主页上引用的演示。
【讨论】:
使用正确的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);
【讨论】:
with drum to the hare
将此与所需的 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));
}
【讨论】: