Pages

Monday, May 11, 2009

Custom Event : Object Oriented Approach

Share it Please

Custom Events In Gwt : Writing Custom events in Gwt is a simple thing . what we need to do is to simply write a interface and use to perform the other actions. Lets write a sample example of writing our own custom event handler.

First lets write a interface which is an agreement with the listener and the class calling the listener,

public interface LoginListener extends EventListener{

public void onLoginSuccess();

public void onLoginFailure();

}

I used java.util.EventListener interface which is a base interface for all types of events.

Now lets write a class which uses this interface ,

public class LoginPage extends Composite {

private HorizontalPanel panel;

private TextBox userName,password;

private Button submit;

private ArrayList listenerList=new ArrayList();

public LoginPage() {

panel=new HorizontalPanel();

userName=new TextBox();

password=new TextBox();

submit=new Button("Submit");

submit.addClickListener(new ClickListener(){

public void onClick(Widget sender) {

for(Iterator it=listenerList.iterator();it.hasNext();){

LoginListener listener=(LoginListener)it.next();

if(userName.getText().equalsIgnoreCase("jagadesh")){

listener.onLoginSuccess();

}else{

listener.onLoginFailure();

}

}

}

});

panel.add(userName);

panel.add(password);

panel.add(submit);

initWidget(panel);

}

public void addListener(LoginListener listener){

if(listenerList!=null){

listenerList.add(listener);

}

}

public void removeListener(LoginListener listener){

if(listenerList!=null){

listenerList.remove(listener);

}

}

}

Now lets make a code walk , in the above code I just created a arraylist which holds all the event listeners. I have written 2 methods which adds a listener and one for removing a existing listener in the arraylist.meanwhile when we click the submit button it gets the listeners in the arratlist and checks whether entered username is valid. If it is it calls inLoginSuccess() and if invalid it calls onLoginFailure().

Now lets look at the onModuleLoad class,

public class Application implements EntryPoint ,LoginListener{

public void onModuleLoad() {

LoginPage page=new LoginPage();

page.addListener(this);

RootPanel.get().add(page);

}

public void onLoginSuccess() {

Window.alert("You Entered The Corret User Name");

}

public void onLoginFailure() {

Window.alert("You Entered A Invalid user Name");

}

}

I just created a instance for the login page and added it to the root panel . I added a LoginListener to the page. U can see the methods invoked according to the entered username.

No comments :

Post a Comment