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 :

setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

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);

desktop.browse(uri);

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;
import java.net.URI;

public class LinkLabel extends JLabel {

 private String url;

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

 setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

 setForeground(c);

 setText(text);

 this.url=url;

 LinkLableListener linkLabelListener=new LinkLableListener();

 addMouseListener(linkLabelListener);

 }

 class LinkLableListener extends MouseAdapter{

 @Override
 public void mouseClicked(MouseEvent e){

 try{
 Desktop desktop=Desktop.getDesktop();

 URI uri=new URI(url);

 desktop.browse(uri);
 }catch(Exception ex){}

 }

}

Advertisements
This entry was posted in Swing. Bookmark the permalink.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s