Using List Components

December 2006 [Revision number: V1-1]  
In this tutorial, you use NetBeans Visual Web Pack 5.5 to create an application that uses a Listbox component that supports multiple selection. When you choose one or more items from the listbox and click the Submit button, the application shows the selected items in a text area. 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
  Content on this page applies to Netbeans 5.5 Visual Web Pack

This tutorial works with the following resources

NetBeans Visual Web Pack 5.5 is compatible with all supported servers and with both the J2EE 1.4 and Java EE 5 platforms. This tutorial highlights Visual Web Pack features that work with the checkmarked resources in the table below.

Application Server works withSun Java System Application Server 9
works withTomcat
works withJBoss
works withBEA WebLogic
JavaServer Faces Components/
Java EE Platform
works with1.2 with Java EE 5*
works with1.1 with J2EE 1.4
Travel Database requiredNot Required
BluePrints AJAX Component Library not requiredNot Required

* Only the Sun Java System Application Server supports Java EE 5.

For detailed information about supported servers and the Java EE platform, see NetBeans Visual Web Pack 5.5 Installation Instructions.

Creating the Page

  1. Create a new web application project and name it ListExample.

    The following figure shows a preview of the page that you will create in the steps that follow.

    Figure 1: Listbox Example: First Pass
    Figure 1: Sample Page Design
  2. From the Basic section of the Components Palette, drag a Listbox component and drop it on the page, and then click and drag the right edge of the component to make it wider.

    The Outline window lists the components that are associated with the Listbox component. The Listbox component itself, listbox1, keeps track of all items in its list. The listbox is associated with listbox1DefaultOptions, a non-visual component that contains the list of items that the listbox displays, and also tracks the items selected in the listbox.
  3. Set the Listbox component's multiple property to True by selecting the checkbox next to the property 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 Button component from the Palette and drop it on the page to the right of the listbox. Change the text of the button to Submit.
  5. Drag a Text Area component onto the page and drop it under the listbox, and then make the component as wide as the listbox.

    The text area will be used to display the items that are selected in the listbox.

Designing and Preserving Listbox Properties

This application needs to preserve listbox information throughout the user's session. The technique for preserving user session data is to save the data in properties of the managed bean SessionBean1, which is in session scope. In this section, you add two properties to SessionBean1 to store the listbox data.
  1. In the Outline window, right-click SessionBean1 and choose Add > Property from the pop-up menu.

    Note: If the Add menu does not appear, close the pop-up menu and then reopen it.

    The New Property Pattern dialog box appears, shown completed in Figure 2. You use this dialog box to create properties for the session bean.

    Figure 2: New Property Pattern Dialog Box
    Figure 2: New Property Pattern Dialog Box
  2. Type listOptions in the Name field.
  3. Type Option[] in the Type field.

    Note: You will add the import statement for the Option class in the next section.
  4. Click OK to create the property.

    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.
  5. Create a SessionBean1 property called choices of type String[] to hold the values of the currently selected items.

    1. In the Outline window, right-click SessionBean1 and choose Add > Property.
    2. In the New Property Pattern dialog box, enter choices for Name and String[] for Type, and then click OK.

    Note: You will not be able to see the new properties under the SessionBean1 node until you add the import statement for the Options class to SessionBean1 in the next section.

Initializing the Listbox Properties

In this section, you initialize the values of the two session bean properties that you created in the previous section. You also populate the listOptions property with an initial set of items for the listbox.
  1. In the Outline window, double-click SessionBean1 to open its source code in the Java Editor.
  2. In the Java source file, right-click and choose Fix Imports to open the Fix Imports dialog box.

    You use this dialog box to add the import statement for the Option class, which represents a single item in the listbox.
  3. In the Fix Imports dialog box, click the drop-down list under Fully Qualified Name and choose the correct Option class from the list.

    • If your application is based on Java EE 5, choose com.sun.webui.jsf.model.Option.
    • If your application is based on J2EE 1.4, choose com.sun.rave.web.ui.model.Option.
  4. Add the following bold lines of code to the SessionBean1 constructor.

    Code Sample 1: Options Property for Java EE 5 Application
    public SessionBean1() {
      // Initialize property values and add 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 third line in bold in the code sample above initializes the listOptions property. The next three lines add items 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 final line of code initializes the choices property to ensure that nothing is selected by default.
  5. Open Page1 in the Visual Designer.
  6. In the Outline window, expand the SessionBean1 node and verify that there are nodes for the listOptions and choices properties.

Binding the Properties to the Listbox

In this section you bind the items and selected properties of listbox1 to the appropriate properties of SessionBean1. You bind these properties to link the values of the component properties to the values of the bean properties.

  1. In 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 3: Bind to an Object
  3. Click OK.

    The listbox's items property is now bound to the listOptions array of SessionBean1.
  4. In the Properties window for the listbox, click the ellipsis (...) button for the selected property, which is under the Data section of the Properties window.

    The property editor for the selected property opens with the title "listbox1 - selected".
  5. Select SessionBean1 > choices and click OK.

    The listbox's selected property is now bound to the choices array of SessionBean1.

Displaying the Selected Listbox Items

In this section, you add behavior to the Submit button that does two things: gets the list of currently selected items from SessionBean1, and displays the list in the text area.

  1. In the Visual Designer, double-click the Submit button.
  2. Add the following bold event handler code to the button1_action() method.

    Note: After inserting the code, you can press Ctrl-Shift-F to automatically reformat the code.

    Code Sample 2: Button1 Event Handler
    public String button1_action() {
      // Get the current selections from 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 textArea1
      getTextArea1().setValue(showSelections);
      return null;
    }
  3. Click the green arrow Run Project toolbar icon in the main toolbar, or choose Run > Run Main Project, to build and run the application.
  4. In the running application, select one or more items in the listbox and click the Submit button.

    To select multiple items, use Ctrl-click. When you click the Submit button, the values for the selected items appear in the text area. Figure 4 shows the running application.

    Figure 4: Listbox: Final Page
    Figure 4: Listbox Application Running in Browser

Adding and Removing Items From the Listbox

In this final section, you create buttons that 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.

    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;
    }
     
    Note: Your code will have an error on the line for getSessionBean1().addOption() because that method has not yet been added to the session bean.
  5. Open the Outline window, and then right-click the button3:Remove node and choose Edit action Event Handler.
  6. Insert the bold code below in the button3_action method.

    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;
    }
     
    Note: Your code will have an error on the line starting with getSessionBean1().removeOptions because that method has not yet been added to the session bean.
  7. 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 to add the new property.
  9. In the Outline window, double-click SessionBean1 to open its 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. Now that the new methods have been added to the session bean, click the Page1.jsp tab to open that page, and then click the Design button to return to the Visual Designer.

    The error condition is still showing on that page.
  13. Click the Refresh button Refresh  button icon in the Visual Designer toolbar to remove the error condition and display the components on the page.
  14. 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 5: Adding an Item to the Listbox
    Figure 5: Adding an Item to the Listbox
 

See Also:


This page was last modified: December 6, 2006


Copyright and Trademark Notice