Java JLabel create hyper link label

Description

Java JLabel create hyper link label


import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URI;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {
  public static void createHiperLink(JLabel label, final String url, String text) {
    label.setToolTipText(url);/*from  ww  w  .j a v a  2s .co m*/
    label.setText("<html><a href=\"\">" + text + "</a></html>");
    label.setCursor(new Cursor(Cursor.HAND_CURSOR));
    label.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        try {
          Desktop.getDesktop().browse(new URI(url));
        } catch (Exception ex) {
          throw new RuntimeException(ex);
        }
      }
    });
  }

  public Main() {
    super("Link JLabel with JTextField");

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    JLabel nameLabel = new JLabel();
    createHiperLink(nameLabel,"https://demo2s.com","Java demo from demo2s.com.");

    add(nameLabel);

  }

  public static void main(String[] args) {
    Main frame = new Main();
    frame.pack();
    frame.setVisible(true);
  }
}



PreviousNext

Related