How to create hyperlink JLabel




Create class that extend JLabel and override some properties of JLabel and customise as show in below code,

 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 java.util.logging.Level;  
 import java.util.logging.Logger;  
 import javax.swing.JLabel;  
 public class HyperLinkLabel extends JLabel {  
   public HyperLinkLabel(final String url, final String anchor) {  
     this.setText(anchor);  
     this.setForeground(Color.BLUE);  
     this.setCursor(new Cursor(Cursor.HAND_CURSOR));  
     this.addMouseListener(new MouseAdapter() {  
       @Override  
       public void mouseReleased(MouseEvent e) {  
         try {  
           Desktop.getDesktop().browse(new URI(url));  
         } catch (URISyntaxException ex) {  
           Logger.getLogger(HyperLinkLabel.class.getName()).log(Level.SEVERE, null, ex);  
         } catch (IOException ex) {  
           Logger.getLogger(HyperLinkLabel.class.getName()).log(Level.SEVERE, null, ex);  
         }  
       }  
       @Override  
       public void mouseEntered(MouseEvent e) {  
         setText("<html><u>" + anchor + "</u></html>");  
       }  
       @Override  
       public void mouseExited(MouseEvent e) {  
         setText(anchor);  
       }  
     });  
   }  
 }  

Use in your project,

 javax.swing.JLabel myLable = new HyperLinkLabel("http://www.how2java.com", "How2Java");  

or

 HyperLinkLabel myLable = new HyperLinkLabel("http://www.how2java.com", "How2Java");  

First Parameter is your destination URL and second is anchor text.


2 comments:

  1. when i run it displying blank jframe..what's the problem?

    ReplyDelete
  2. Thanks a lot ! Very useful !

    ReplyDelete