Using Client-side Rendering Features in Selector Components
Contributed by Gowri Tangirala
In this tutorial, you use the NetBeans Visual Web JSF framework to create an application that uses a JSF 1.2 (Woodstock) 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.
Contents
To follow this tutorial, you need the following software and resources.
| NetBeans IDE |
Web & Java EE version 6.1 or 6.0 |
| Java Developer Kit (JDK) |
Version 6 or
version 5 |
JavaServer Faces Components/
Java EE Platform |
1.2 with Java EE 5* or
1.1 with J2EE 1.4
|
| GlassFish Application Server |
V2 |
| Travel Database |
Not required |
* To take advantage of NetBeans IDE's Java EE 5 capabilities, use an application server that is fully compliant with the Java EE 5 specification, such as the GlassFish Application Server V2 UR2. If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds.
For detailed information about the
supported servers and Java EE platform, see the Release Notes.
Note for NetBeans IDE 6.1 users:
- Creating a project in NetBeans 6.1 includes new options which can be left at the default. For example, the Use Dedicated Folder for Storing Libraries checkbox may be left unselected.
- NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.
Creating the Project
In this tutorial, you create a single-page web application. You begin by laying out the page, as shown in the following figure.
Designing the Page
Note: NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.
- Create a new web application named
ListboxExample that uses the Visual Web JavaServer Faces framework. The application's Page1.jsp file opens in the Visual Designer.Note: Creating a project in NetBeans 6.1 includes new options which can be left at the default. For example, the Use Dedicated Folder for Storing Libraries checkbox may be left unselected.
- From the Basic section of the Palette, drag a Listbox component to the upper left corner of the page. In the Properties window, change its
id property to personDD.
-
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.
-
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 the Text Area component'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 (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
Note: NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.
- In the Navigator window, right-click SessionBean1 and choose Edit Java Source.
- Type
Option[] listOptions; in the sessionBean1 class.
-
Right-click on the listOptions and select Insert Code option from the context menu which shows the Getter and Setter option as shown in the following figure.
The Generate Getter and Setter dialog box opens.
-
Select the listOptions checkbox and select Generate to add the getter and setter methods for listOptions as shown in the following figure.
- Right click on the page and select fix imports. Choose
com.sun.webui.jsf.model.Option from the list.
-
Click OK.
The listOptions array contains 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 the 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 component.
- Add the following lines of code in the
SessionBean1 constructor. Comments are included in this and the following examples to explain the code.
| Code Sample 1: Initializing propert values and adding choices |
// 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 Properties to the Listbox Component
Now we bind the items property oflistbox1 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.
Note: NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.
-
Open Page1.jsp 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 the following figure.
- Click OK.
-
In the Properties window for the Listbox, click the ellipsis (...) button for the selected property. This property is under the Data section in the Properties window.
The listbox1 - selected dialog box opens.
- Select SessionBean1 > choices as the binding target and click OK.
Displaying the Selected Listbox Items
Now you add behavior to the Listbox component 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.
Note: NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.
- In the Visual Designer, right click on Listbox component and select Edit Event Handler > processValueChange.
- 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.
Code Sample 2: The listbox1_processValueChange() Method. |
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);
}
|
- 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.
Code Sample 3: onChange property |
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.
The following figure shows the deployed 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.
Note: NetBeans IDE 6.1 features on-demand binding. Where components require Java coding, you must now manually add the binding attribute to components in a Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute. For more information, see the On-demand Binding Attribute Wiki.
- Open 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.
Code Sample 4: Addition to 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] = 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
}
}
|
- Open the Visual Designer. drag a Button component from the palette and place it the right of the Listbox component.
Change the text of the button to
Add.
- Drag a second button from the palette and place it 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 Internet Explorer 7.
-
Double-click the Add button and insert the following code in the button1_action method with following code.
Code Sample 5: button1_action Method |
public String button1_action() {
// Add a new generated item to the listbox1 component
getSessionBean1().addOption();
getTextArea1().setText("New Item Added");
return null;
}
|
- Open the Visual Designer. Double-click the
Remove button.
-
Replace the button2_action method with the following code.
Code Sample 6: button2_action Method |
public String button2_action() {
// Remove the selected item or items
getSessionBean1().removeOptions((String[])getListbox1().getSelected());
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 the following figure. To remove one or more items, select the items and click the Remove button.
Summary
In this tutorial, you used the NetBeans Visual Web JSF framework to create an application that uses a multi-select listbox and a text area using Ajax functionality.
See Also
This page was last modified: April 15, 2008