1.3. Control Listener Type 2 Example

The second type of control listener binding uses the ActionListener interface to provide compile time safety. This compile time binding also supports code refactoring using modern IDE tools.

public class ControlListenerType2Page extends Page {

    /* Public scope controls are automatically added to the page. */
    @Bindable protected ActionLink myLink = new ActionLink();

    @Bindable protected String msg;

    // ------------------------------------------------------------ Constructor

    /**
     * Create a new Page instance.
     */
    public ControlListenerType2Page() {
        myLink.setActionListener(new ActionListener() {
            public boolean onAction(Control control) {
                 msg = "ControlListenerPage#" + hashCode()
                 + " object method <tt>onAction()</tt> invoked.";

             return true;
            }
        });
    }
    
}

In the Page class we create an ActionLink called myLink. In the Page constructor we set the control's action listener to an annonymous inner class which implements the onAction(). When a user clicks on myLink control it will invoke the action listener method onAction().

As with our previous example, in the page template we define a HTML link and have the myLink control render the link's href attribute:

<html>
  <head>
    <link type="text/css" rel="stylesheet" href="style.css"></link>
  </head>
  <body>
  
  Click myLink control <a href="$myLink.href">here</a>.

  #if ($msg)
    <div id="msgDiv"> $msg </div>
  #end

  </body>
</html>

At runtime this page would be rendered as:

Click myLink control here.

When a user clicks on the link the onAction() method is invoked. This method then creates the msg model value, which is rendered in the page as:

Click myLink control here.

ControlListenerPage#12767107 object method onAction() invoked.