Java Swing How to - Create hyperlinks Label








Question

We would like to know how to create hyperlinks Label.

Answer

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 java.util.logging.Level;
import java.util.logging.Logger;
//ww  w. j a  v a  2 s. c  om
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JFrame {
  private JPanel pan = new JPanel();

  private JLabel website = new JLabel();

  public Main() {
    this.setSize(300, 100);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    website.setText("<html> Website:<a href=''>http://www.java2s.com/</a></html>");
    website.setCursor(new Cursor(Cursor.HAND_CURSOR));
    pan.add(website);
    this.setContentPane(pan);
    this.setVisible(true);
    goWebsite(website);
  }

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

  }

  private void goWebsite(JLabel website) {
    website.addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent e) {
        try {
          try {
            Desktop.getDesktop().browse(new URI("http://www.java2s.com"));
          } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
          }
        } catch (URISyntaxException ex) {

        }
      }
    });
  }
}