Listbox Components Using Ajax Functionality

In this tutorial, you use the Visual Web Pack 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 Ajax functionality. In addition to the Listbox component, these concepts apply to the following components: Drop Down List, Checkbox Group, and Radio Button Group.


Creating the Page

  • Create a new web application project and name it ListboxExample.
            Figure 1 shows the page that you will create in the following steps.


  • From the Basic section of the Components Palette, drag a Listbox component and drop it on the page.
  • 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     
  • Drag a Text Area component from the Basic section of the palette. Place this component under the Listbox. The text area will be used to display the items that are selected in the listbox.
  • Set text area's rows property to 10 by setting its value in the 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 ( 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.

  * In the Navigator window, right-click SessionBean1 and choose Edit Java Source.
  * Type Option[[[ | []] listOptions;  in sessionBean1 class.
  * Now right click on the listOptions and select Insert Code option from the context menu which shows the Getter and Setter option 

as shown in Figure 2. File:image7_HowToUseClientSideRenderingFeaturesInSelectorComponents.gif

  * Selecting Getter and Setter... brings up a dialog. Now select the listOptions checkbox and select Generate to add the getter and setter methods for listOptions as shown in Figure 3.


  * Right click on the page and select fix imports. Choose com.sun.webui.jsf.model.Option from the list.
  * 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.

  * Type String[[[ | []] choices;  in sessionBean1 class.
  * Right click on choices and select Insert Code option to set its Getter and Setter methods. Add them, the same way you did for listOptions.

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.

  • Add the following lines of code in the SessionBean1 constructor. Comments are included in this and the following examples to explain the code.
// 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 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 The process of binding properties actually links the value of the component property to the value of a bean property.
  * Open Page1 in the Visual Designer. Right-click the Listbox component, and then choose Bind to Data. The Bind to Data dialog box opens.
  * On the Bind to an Object tab, select SessionBean 1 > listOptions, as shown in Figure 4:


  * Click OK.
  * 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     
     The listbox1 - selected dialog box opens.
  * 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.

  * In the Visual Designer, right click on Listbox component and  select Edit Event Handler --> processValueChange event.
  * Add the following event handler code to the listbox1_processValueChange() method. After inserting the code, you can press Alt+Shift+F to automatically format the code. 
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";
    showSelections = "Values chosen:\n" + showSelections;
  // Display the list in the textArea1 text area

* 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.
  • Add the following code to the javascript expression.
document.getElementById('form1:textArea1').refresh('form1:listbox1'); return false;
  • This code is actually using the Ajax functionilty in refreshing the TextArea without refreshing the entire page.
  • Click the green arrow in the main toolbar, or choose Run > Run Main Project to build and run the application.
  • 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.
  • Figure 5 shows the running application.


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.

  • Go back to the Visual Designer.
  • In the Navigator window, double-click SessionBean1 to open the source code in the Java Editor.
  • In SessionBean1 type int counter = 0;
  • Right click on the counter and select Insert Code option to set its Getter and Setter methods. Add them, the same way you did for listOptions and choices.
  • Insert the following methods after the SessionBean1 constructor.

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 | 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 | i]].getValue().equals(selectedValues[J])) {
               // this item will be removed
               found = true;
           if (!found) {
             // since this item was not selected, add it to the updated list
             newOpts[[K | k]] = current[I];
         setListOptions(newOpts);  // update the list
         setChoices(null);  // remove the existing selected values

* Go back to the Visual Designer
* Add a Button, and change the text of the button to Add.
* Add a second Button under the Add button. Change the text of this button to Remove.

Note: Buttons should be either placed in a Grid or their size should be set explicitly in the property sheet to avoid rendering problems in IE7.

* Double-click the Add button and insert the following code in the button1_action method. 
public String button1_action() {
  // Add a new generated item to the listbox1 component
  getTextArea1().setText("New Item Added");
  return null;

  • Go back to the Visual Designer and then double-click the Remove button.
  • Insert the following code in the button2_action method.
public String button2_action() {
  // Remove the selected item or items
  getTextArea1().setText("Selected Items Removed");
  return null;

  • 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 6. To remove one or more items, select the items and click the Remove button. File:image5_HowToUseClientSideRenderingFeaturesInSelectorComponents.jpg

Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo