How to create hyperlink with JLabel in Java Swing
- Details
- Written by Nam Ha Minh
- Last Updated on 06 July 2019   |   Print Email
In this Java Swing tutorial, you will learn how to create a hyperlink by extending the JLabel component, as Swing doesn’t have any built-in components that can display hyperlinks.
First, create a JLabel as normal like this:
JLabel hyperlink = new JLabel("Visit CodeJava");
Set its text color looks like standard hyperlink (blue):
hyperlink.setForeground(Color.BLUE.darker());
To make the mouse cursor changes to a hand icon when the user moves the mouse over the label, set its cursor like this:
hyperlink.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
And to make the label clickable, add a mouse listener class to the JLabel:
hyperlink.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { // the user clicks on the label } @Override public void mouseEntered(MouseEvent e) { // the mouse has entered the label } @Override public void mouseExited(MouseEvent e) { // the mouse has exited the label } });
We override the mouseClicked() method to handle the event in which the user clicks on the hyperlink. And in this method, we can use the Desktop class to open the associated hyperlink, for example:
@Override public void mouseClicked(MouseEvent e) { try { Desktop.getDesktop().browse(new URI("http://www.codejava.net")); } catch (IOException | URISyntaxException e1) { e1.printStackTrace(); } }
The operating system will open an appropriate program that associates with the URL, typically a browser if the link is a website URL or an email program if the link is an email address.
To make the text underlined when the user moves the mouse over the hyperlink, we can use this trick: set HTML code for the text with the <a> tag. So you can override the mouseEntered() method like this:
hyperlink.setText("<html><a href=''>Visit CodeJava</a></html>");
And when the mouse has exited, set the text back to original:
hyperlink.setText("Visit CodeJava");
The following code shows you a complete example program that displays a hyperlink in a window, based on the techniques described above:
package net.codejava.swing.hyperlink; import java.awt.Color; import java.awt.Cursor; import java.awt.Desktop; import java.awt.FlowLayout; import java.awt.HeadlessException; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; /** * This Java Swing program demonstrates how to create a hyperlink. * * @author www.codejava.net * */ public class HyperlinkDemo extends JFrame { private String text = "Visit CodeJava"; private JLabel hyperlink = new JLabel(text); public HyperlinkDemo() throws HeadlessException { super(); setTitle("Hyperlink Demo"); hyperlink.setForeground(Color.BLUE.darker()); hyperlink.setCursor(new Cursor(Cursor.HAND_CURSOR)); hyperlink.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { try { Desktop.getDesktop().browse(new URI("http://www.codejava.net")); } catch (IOException | URISyntaxException e1) { e1.printStackTrace(); } } @Override public void mouseExited(MouseEvent e) { hyperlink.setText(text); } @Override public void mouseEntered(MouseEvent e) { hyperlink.setText("<html><a href=''>" + text + "</a></html>"); } }); setLayout(new FlowLayout()); getContentPane().add(hyperlink); setSize(400, 200); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new HyperlinkDemo().setVisible(true);; } });; } }
Run this program you can see the following program:
Mouse the mouse over the link and you see it is underlined and brighter. Click the link and the default browser will be launched to open the hyperlink.
Going further, we can extend the JLabel class to create our custom component so it can be reused. We call it JHyperlink - with the source code as below:
package net.codejava.swing.hyperlink; import java.awt.Color; import java.awt.Cursor; import java.awt.Desktop; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.JLabel; import javax.swing.JOptionPane; /** * A hyperlink component that is based on JLabel. * * @author www.codejava.net * */ public class JHyperlink extends JLabel { private String url; private String html = "<html><a href=''>%s</a></html>"; public JHyperlink(String text) { this(text, null, null); } public JHyperlink(String text, String url) { this(text, url, null); } public void setURL(String url) { this.url = url; } public JHyperlink(String text, String url, String tooltip) { super(text); this.url = url; setForeground(Color.BLUE.darker()); setToolTipText(tooltip); setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { setText(String.format(html, text)); } @Override public void mouseExited(MouseEvent e) { setText(text); } @Override public void mouseClicked(MouseEvent e) { try { Desktop.getDesktop().browse(new URI(JHyperlink.this.url)); } catch (IOException | URISyntaxException e1) { JOptionPane.showMessageDialog(JHyperlink.this, "Could not open the hyperlink. Error: " + e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } } }); } }
As you can see, this component allows the client code to specify tooltip text besides the text and link. And the following code is a demo program:
package net.codejava.swing.hyperlink; import java.awt.FlowLayout; import java.awt.HeadlessException; import javax.swing.JFrame; import javax.swing.SwingUtilities; /** * This Java Swing program demonstrates how to use JHyperlink custom component. * * @author www.codejava.net * */ public class JHyperlinkDemo extends JFrame { private JHyperlink linkWebsite = new JHyperlink("Visit our website"); private JHyperlink linkEmail = new JHyperlink("Email Us"); public JHyperlinkDemo() throws HeadlessException { setTitle("Swing Hyperlink Demo"); setLayout(new FlowLayout(FlowLayout.CENTER, 50, 10)); linkWebsite.setURL("http://www.codejava.net"); linkWebsite.setToolTipText("Visit http://www.codejava.net"); linkEmail.setURL("mailto:info@codejava.net"); linkEmail.setToolTipText("Send an email to info@codejava.net"); getContentPane().add(linkWebsite); getContentPane().add(linkEmail); setSize(400, 200); setVisible(true); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new JHyperlinkDemo().setVisible(true); } }); } }
Run this program and you can see:
Click “Visit our website” and the default browser opens the website. Click “Email Us” and you can see the default email program prepares a new email.
Other Java Swing Tutorials:
- Java Swing Hello World Tutorial for Beginners Using Text Editor
- JFrame basic tutorial and examples
- JPanel basic tutorial and examples
- JLabel basic tutorial and examples
- JTextField basic tutorial and examples
- JButton basic tutorial and examples
- JComboBox basic tutorial and examples
- JCheckBox basic tutorial and examples
- JList basic tutorial and examples
Comments