Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Underline a JLabel on MouseEnter

I tried to change the font, by using:

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

But there's only 4 styles here, Plain, Bold, Italic, Bold+Italic.

I want it to work like a link in HTML, the JLabel gets underlined when I hover the mouse cursor on it.

like image 749
user1665700 Avatar asked Dec 06 '25 08:12

user1665700


1 Answers

To clarify (or not :-) the confusion introduced in my comments to mKorbel

Never create a Font out of the blue: it will most probably clash with all other fonts in the application. Instead, grab the default (either from the component instance as in the snippet shown below or the UIManager, doesn't matter) and derive.

For deriving using attributes (shamelessly steeling from mKorbel's answer), that's something like

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"));

But beware: that will not yet give you any hyperlink functionality! So in case a Hyperlink is what you are really after, consider using a full-fledged component with such a functionality, like f.i. JXHyperlink in the SwingX project. You might want to run the demo referenced on its project home.

like image 108
kleopatra Avatar answered Dec 07 '25 20:12

kleopatra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!