Creating a URL JLabel in Swing

So, you need a simple clickable URL JLabel in your Swing application? You can, of course, use third party libraries to do this, but why add another dependency for a single component when can easily write one in 5 minutes.

So what do we want for this JLabel:

  • to click on it and go to an URL
  • to have a hand cursor on mouse over
  • the text to be underlined just like a real link

We’ll write a class that extends JLabel and a mouse adapter that will take care of opening the link. As the mouse adapter will be used only for this label, we’ll add it as a private member class. Here is the code:

package insidecoding.swing

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URI;
import javax.swing.JLabel;

/**
 *
 * @author ludovicianul
 */
public class URLLabel extends JLabel {

    private String url;

    public URLLabel() {
        this("","");
    }

    public URLLabel(String label, String url) {
        super(label);

        this.url = url;
        setForeground(Color.BLUE.darker());
        setCursor(
                new Cursor(Cursor.HAND_CURSOR));
        addMouseListener(
                new URLOpenAdapter());
    }

    public void setURL(String url) {
        this.url = url;
    }

    //this is used to underline the text
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        g.setColor(Color.blue);

        Insets insets = getInsets();

        int left = insets.left;
        if (getIcon() != null) {
            left += getIcon().getIconWidth() + getIconTextGap();
        }

        g.drawLine(left, getHeight() - 1 - insets.bottom, (int) getPreferredSize().getWidth()
                - insets.right, getHeight() - 1 - insets.bottom);
    }

    private class URLOpenAdapter extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (Desktop.isDesktopSupported()) {
                try {
                    Desktop.getDesktop().browse(new URI(url));
                } catch (Throwable t) {
                    //
                }
            }
        }
    }
}

I think the code is pretty self-explanatory:

  • in the constructor we set the label color to a darker blue, we set the mouse over cursor to Hand Cursor and we register the mouse click listener
  • we use the paint() method to underline the label’s text
  • the mouse adapter uses the Continue reading