How to write a Custom swing component ?

Scenario :

make label, when user click on it go to specific URL.also mouse cursor change to hand symbol.

How :

1 – we must provide a class and extend JLabel class

public class LinkLabel  extends JLabel {

2 – users [other developers] must initiate our component with  3 Arguments  :

URL  ,   Text , Color.

Therefore , we must provide a constructor with 3 arguments for our component :

public LinkLabel(String url, String text, Color c)

3 – how change mouse cursor ? easy ! in constructor write following code :


4 – how open default browser of user and show specific URL ?

Desktop class comes with JDK 6  provide powerful solution for this work.

4-1 ) import this package : java.awt.Desktop

4-2 ) we must write Mouse Listener for our component and catch mouse click then

show specific URL into user’s default broswer :

Desktop desktop=Desktop.getDesktop();
URI uri=new URI(url);


5 – complete !

import java.awt.Color;
import java.awt.Cursor;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.awt.Desktop;

public class LinkLabel extends JLabel {

 private String url;

 public LinkLabel(String url,String text,Color c)





 LinkLableListener linkLabelListener=new LinkLableListener();



 class LinkLableListener extends MouseAdapter{

 public void mouseClicked(MouseEvent e){

 Desktop desktop=Desktop.getDesktop();

 URI uri=new URI(url);

 }catch(Exception ex){}



This entry was posted in Swing. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s