Listbox Components Using Ajax Functionality

By Gowri Tangirala
November 2007
 
 
In this tutorial, you use the Visual Web Pack development environment (the IDE) to create an application that uses a multi-select listbox. When you choose one or more items from the listbox , the application shows the selected items in a text area using the Ajax functionality. In addition to the Listbox component, these concepts apply to the following components: Drop Down List, Checkbox Group, and Radio Button Group.
 
Contents
 
Creating the Page
Defining and Preserving Listbox Properties
Initializing the Listbox Properties
Binding the Properties to the Listbox
Displaying the Selected Listbox Items
Adding and Removing Items From the Listbox
[spacer]  
 
Creating the Page
 
  1. Create a new web application project and name it ListExample.

    Figure 1 shows the page that you will create in the following steps.

     
    Figure 1: Listbox Example: Page Design
     
  2. From the Basic section of the Components Palette, drag a Listbox component and drop it on the page.

    The Outline window lists the components that are associated with the Listbox component. The Listbox itself (listbox1) keeps track of all items in the list. The Listbox is associated with listbox1DefaultOptions, a non-visual component that contains the list of items the Listbox displays and also tracks the items selected in the Listbox.

  3. Set the Listbox's multiple property to True by selecting the checkbox in the Properties window.

    The multiple property is under the Data section of the Properties window. A value of True enables the user to select multiple items in the Listbox.

  4. Drag a Text Area component onto the page. Place this component under the Listbox. The text area will be used to display the items that are selected in the listbox.

  5. Set text area's rows property to 10 by selecting in the Properties window.
 
Designing and Preserving Listbox Properties
 
Each time the client browser requests a web page, a new page is generated on the server in what is called the Request scope. When the new page is initialized, any information previously stored in the page bean (Page1.java) is overwritten. To enable the application to preserve the listbox items across requests, you must save the items in a bean property, which is in Session scope.
  1. In the Outline window, right-click SessionBean1 and choose Edit Java Source.

  2. Type Option[] listOptions in sessionBean1 class.

  3. Now right click on the listOptions and select Insert Code option from the context menu.



  4. From the context menu select Getter and Setter... to add the getter and setter methods for listOptions.

  5. Right click on the page and select fix imports to import  com.sun.web.ui.model.Option.

  6. Click OK.

    The listOptions array will contain objects of type Option. Each object represents an option in the list. Each option contains both a display name and a value. The display name is always a String, but the value can be any kind of object—in this case it is also a String.

    Now you will create a property, called choices, to hold the values of the currently selected items.

  7. In SessionBean1 type String[] choices.

  8. Right click on the choices and select Insert Code option to set its Getter and Setter metods.

Initializing the Listbox Properties
 
In this section, you initialize the values of the two SessionBean properties that you created in the previous section. You also populate the listOptions property with an initial set of items for the listbox.
  1. Add the following bold lines of code above the SessionBean1 constructor. Comments are included in this and the following examples to explain the code.

    Code Sample 1: Options Property
      // Initialize the property values and 
      //add some choices to the listOptions property to get started.
      listOptions = new Option[] {
      new Option("choice1", "My Choice 1"),
      new Option("choice2", "My Choice 2"),
      new Option("choice3", "My Choice 3")};
      choices = new String[] {};
    
    
    
     
    The second line in bold in the code sample above initializes the listOptions property. The next three lines add an item to the listbox. The first parameter (for example, choice1) is the value of the item. This value is captured in the value property of the Listbox component when you select an item. In this case, a String is used, but you can use an instance of any Java class. The second parameter (for example, My Choice 1) is the text displayed in the listbox. The last line initializes the choices property so that nothing is selected by default.
 
Binding the Properties to the Listbox
 
Now bind the items property of listbox1 and the choices array to the properties in SessionBean1.java. The process of binding properties actually links the value of the component property to the value of a bean property.
  1. Open Page1 in the Visual Designer. Right-click the Listbox component, and then choose Bind to Data. The Bind to Data dialog box opens.

  2. On the Bind to an Object tab, select SessionBean 1 > listOptions, as shown in Figure 3:

    Figure 3:  Bind to an Object
    Figure 2 : Bind to an Object
     
  3. Click OK.

  4. In the Properties window for the Listbox, click the ellipsis (...) button for the selected property. This property is under the Data section of the Properties window.

    The listbox1 - selected dialog box opens.

  5. On the Bind to an Object tab, select SessionBean1 > choices and click OK.
 
Displaying the Selected Listbox Items
 
Next, add behavior to the Listbox  that does two things: gets the list of currently selected items from the SessionBean and displays the list in the text area without refreshing the entire page using Ajax functionality.
  1. In the Visual Designer, right click on Listbox component and  select Edit Event Handler --> processValueChange event.

  2. Add the following bold event handler code to the listbox1_processValueChange() method. After inserting the code, you can press Ctrl-Shift-F to automatically format the code.

    Code Sample 2: ListBox1  Event Handler
    public String listbox1_processValueChange(ValueChangeEvent event) {
      //set the current selections in the SessionBean1
      getSessionBean1().setChoices((String[]) listbox1.getSelected());
      //get the current selections from the SessionBean1
      String[] mySelections = getSessionBean1().getChoices();
      String showSelections = "";
      if (mySelections != null) {
        // Create a list of the values of the selected items
        for (int i = 0; i < mySelections.length; i++)
          showSelections = showSelections + mySelections[i] +"\n";
      }
      if (showSelections.equals(""))
        showSelections = "nothing selected";
      else
        showSelections = "Values chosen:\n" + showSelections;
      // Display the list in the textArea1 text area
      getTextArea1().setValue(showSelections);  
    }
     
  3. In the Visual Designer, in the properties window for the Listbox, click the ellipsis(...) button for the onChange property. This property is under the JavaScript section of the propertieswindow.

  4. Add the following code to the javascript expression.

    document.getElementById('form1:textArea1').refresh('form1:listbox1'); return false;

  5. This code is actually using the Ajax functionilty in refreshing the TextArea without refreshing the entire page.

  6. Click the green arrow in the main toolbar, or choose Run > Run Main Project to build and run the application.

  7. In the running application, select one or more items in the Listbox and the selected items appear in the text area without refreshing the page. To select multiple items, use Control-click.

  8. Figure 4 shows the running application.

     
     
    Figure 3 : Listbox: Final Page

 
Adding and Removing Items From the Listbox
 
In this final section, you create buttons that will add and remove items from the listbox. Each item in the list has both a name and a value. You set the values for a newly added item based on the item's position in the list. You also use the values of the items to determine which items to remove from the list.
  1. Click Design to open the Visual Designer.

  2. Add a Button under the Submit button. Change the text of the button to Add.

  3. Add a second Button under the Add button. Change the text of this button to Remove.

  4. Double-click the Add button and insert the following bold code in the button2_action method. Your code will have an error on the line getSessionBean1().addOption() because that method has not yet been added to the Session Bean.

    Code Sample 3: Button2 Action Method
    public String button2_action() {
      // Add a new generated item to the listbox1 component
      getSessionBean1().addOption();
      getTextArea1().setText("New Item Added");
      return null;
    }
     
  5. Click Design to return to the Visual Designer and then double-click the Remove button.

  6. Insert the following bold code in the button3_action method. Your code will have an error on the line getSessionBean1().removeOptions() because that method has not yet been added to the Session Bean.

    Code Sample 4: Button3 Action Method
    public String button3_action() {
      // Remove the selected item or items
      getSessionBean1().removeOptions((String[])getListbox1().getSelected());
      getTextArea1().setText("Selected Items Removed");
      return null;
    }
     
  7. Click Design to return to the Visual Designer and then, in the Outline window, right-click SessionBean1 and choose Add > Property.

  8. In the New Property Pattern dialog box, set the Name to counter and the Type to int, and then click OK. Right-click the SessionBean1 node and choose Refresh to see the new property under the SessionBean1 node.

  9. In the Outline window, double-click SessionBean1 to open the source code in the Java Editor.

  10. In the SessionBean1 constructor, initialize the counter by inserting the following line after choices = new String[] {};

    counter = 0;

  11. Insert the following methods after the SessionBean1 constructor.

    Code Sample 5: addOption and removeOptions Methods
    public void addOption() {
           // add a new item to the list
           // by creating an updated array that contains the new item
           setCounter(getCounter() + 1);  // counter to assure unique values
           String newItemVal = "newitem"+getCounter();
           Option opt = new Option(newItemVal, "New Item "+getCounter());
           Option[] current = getListOptions();
           Option[] newOpts = new Option[current.length + 1];
           // add the current items to the new array
           for (int i = 0; i  < current.length; i++)
             newOpts[i] = current[i];
           newOpts[current.length] = opt;
           setListOptions(newOpts); // update the list
           setChoices(new String[] {newItemVal}); // select the new item
    }
    
    public void removeOptions(String[] selectedValues) {
           // remove the options that are selected in the list
           // by matching the values to the options
           Option[] current = getListOptions();
           int curLength = current.length;
           if (selectedValues != null) {
             int numSelected = selectedValues.length;
             int newLength = curLength - numSelected;
             Option[] newOpts = new Option[newLength]; // updated list array
             int k = 0;  // counter for the updated list
             boolean found = false;
             for (int i = 0; i < current.length; i++) {
               // scan the current items to identify the ones to remove
               found = false;
               for (int j = 0; j < numSelected; j++) {
                 if (current[i].getValue().equals(selectedValues[j])) {
                   // this item will be removed
                   found = true;
                   break;
                 }
               }
               if (!found) {
                 // since this item was not selected, add it to the updated list
                 newOpts[k] = current[i];
                 k++;
               }
             }
             setListOptions(newOpts);  // update the list
             setChoices(null);  // remove the existing selected values
           }
    }
    
     
  12. Run the application.

    To test the new code, click the Add button to add a new item to the end of the list, as shown in Figure 5. To remove one or more items, select the items and click the Remove button.

     
    Figure 4 : Adding an Item to the Listbox