如何在MouseEnter上为JLabel加下划线

时间:2012-09-12 13:20:39

标签: java html swing fonts jlabel

我尝试使用以下方法更改字体:

jLabel.setFont(new Font("Tahoma",1,20));

但这里只有4种风格,包括Plain,Bold,Italic,Bold + Italic。

我希望它像HTML中的链接一样工作,当我将鼠标光标悬停在它上面时,JLabel会加下划线。

4 个答案:

答案 0 :(得分:6)

澄清(或不是:-)我对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"));

但要注意:那还不会给你任何超链接功能!因此,如果超链接是您真正之后的事情,请考虑使用具有此类功能的完整组件,例如f.i. JXHyperlink in the SwingX project。您可能希望运行其项目主页上引用的演示。

答案 1 :(得分:4)

使用适当的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);

答案 2 :(得分:0)

将此与所需的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);
    }

答案 3 :(得分:0)

 if (CheckBox.isSelected()) {
        Font font = CheckBox.getFont();
        Map attributes = font.getAttributes();
        attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_GRAY);
        CheckBox.setFont(font.deriveFont(attributes));
    }