Tuesday, March 17, 2009

Adding different ActionListeners Programmatically

Here are some sample codes that anyone can use for adding different types of ActionListeners
to a RichCommandButton or RichCommandMenuItem or RichCommandToolbarButton Programmatically.

There might be cases that you need to add actions to some buttons programmatically; This means that you will need to search through the API to find out the appropriate java class of what you need. This Class saves you from this trouble and most of all saves you time!

I came across to this requirement and i think it might be very useful to others.

Also check Edwin Biemond's post for some handy code you might need.

Basically is a Utils Class called RichCommandComponentUtils.java and adds programmatically the following methods:
  1. ActionListener
  2. Action
  3. ResetActionListener
  4. FileDownLoadActionListener
  5. ReturnListener

Each method has it's own MethodExpression method in order to be suitable for the component.
This can be very handy and useful in cases of Dynamically Generating Buttons as Andrej's post.
Of course it can be used where ever you think it is suitable

In a few words the process is this:

In order to have an ActionListener to , lets say a commandButton, porgrammatically we need to do the following steps:
  1. Binding of the Button to a bean e.g. myActionListenerButton.
  2. The ActionListener method which must have the following structure
    public void anActionListener(ActionEvent anActionEvent) { ... }
  3. And the Usage of the RichCommandComponent class as follows:
    RichCommandComponentUtils.addActionListener( this.getMyActionListenerButton(),"#{main_Backing.anActionListener}");
And this is it.

Your button now has another ActionListener.
Here is a sample application that adds different types of listeners to some buttons.

In this sample application Listeners are added to the Buttons on Main and Second pages.
This happens on RenderResponce phase of each page.

NOTE: In the sample application I clear all actionListeners before adding some. This happens because actionListener are added which means that with this sample every time the page is rendered the Buttons will have plus one actionListener.

Feel free to update, fix, improve this Utils class. It is very usefull to me and other improved versions will come. Let me Know of what you think




Related Posts Plugin for WordPress, Blogger...