Share this page 

Have a Label acting as HTML HREF (URLLabel)Tag(s): AWT


[URLLabel.java]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class URLLabel extends Label  {
 private java.applet.Applet applet;
 private URL url;
 private String target = "";
 private Color unvisitedURL = Color.blue;
 private Color visitedURL = Color.green;

 public URLLabel(Applet applet , String url, String text){
   this(applet, url, text, "_self");
   }

 public URLLabel
     (Applet applet , String url, String text, String target){
   super(text);
   setForeground(unvisitedURL);
   try {
    this.applet = applet;
    this.url = new URL(url);
    this.target = target;
    addMouseListener( new Clicked() );
   }
   catch (Exception e) {
    e.printStackTrace();
   }
 }

 public void paint(Graphics g) {
  Rectangle r;
  super.paint(g);
  r = g.getClipBounds();
  g.drawLine(0,
    r.height - this.getFontMetrics(this.getFont()).getDescent(),
    this.getFontMetrics(this.getFont()).stringWidth(this.getText()),
    r.height - this.getFontMetrics(this.getFont()).getDescent());
 }

 public void setUnvisitedURLColor(Color c) {
  unvisitedURL = c;
 }

 public void setVisitedURLColor(Color c) {
  visitedURL = c;
 }

 class Clicked extends MouseAdapter{
  public void mouseClicked(MouseEvent me){
   setForeground(visitedURL);
   applet.getAppletContext().showDocument(url, target);
  }
 }
}
[TestURLLabel.java]
import java.applet.*;
import java.awt.*;

public class TestURLLabel extends Applet {
 public void init() {
  URLLabel ull1 = new URLLabel(this,
      "http://www.rgagnon.com/howto.html",
      "Java How-to");
  add(ull1);
  URLLabel ull2 = new URLLabel(this,
      "http://www.rgagnon.com/bigindex.html",
      "Java How-to BigIndex");
  add(ull2);
  URLLabel ull3 = new URLLabel(this,
      "http://www.rgagnon.com/javadetails/java-0001.html",
      "Java How-to 0001");
  add(ull3);
  URLLabel ull4 = new URLLabel(this,
      "http://www.rgagnon.com/javadetails/java-0002.html",
      "Java How-to 0002");
  add(ull4);
  validate();
  }
}
[testapplet.html]
<HTML><HEAD></HEAD><BODY>
 <APPLET CODE="TestURLLabel.class"
         NAME="myApplet"
         HEIGHT=200 WIDTH=200>
</APPLET></BODY></HTML>
Try it here.