how to create hyperlink with jlabel in java swing+

In Java Swing, you can create a hyperlink using a JLabel component and the setForeground() and setCursor() methods.

Here's an example of how to create a hyperlink with JLabel:

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.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class HyperlinkExample {
    public static void main(String[] args) {
        // Create a JLabel with hyperlink text
        JLabel label = new JLabel("<html><u>Visit Java.com</u></html>");
        label.setForeground(Color.BLUE.darker());
        label.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        
        // Add a listener to open the hyperlink when the label is clicked
        label.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                try {
                    Desktop.getDesktop().browse(new URI("https://www.java.com/"));
                } catch (IOException | URISyntaxException ex) {
                    ex.printStackTrace();
                }
            }
        });
        
        // Add the label to a panel and display the panel
        JPanel panel = new JPanel();
        panel.add(label);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}
Sourc‮i.www:e‬giftidea.com

In this example, we create a JLabel with the HTML text "<html><u>Visit Java.com</u></html>", which displays underlined text that looks like a hyperlink. We also set the foreground color of the label to blue and change the cursor to a hand cursor to indicate that it is clickable.

We add a mouse listener to the label that opens the hyperlink in a web browser when the label is clicked. We use the Desktop class to open the default web browser and the browse() method to open the specified URI.

Finally, we add the label to a panel and display it in a frame. When the user clicks the label, the hyperlink is opened in a web browser.