Horizontal Layout Widget

The component model supplied to the "Horizontal Layout Widget" is a collection of components. The role of this widget is to iterate over that collection, delegating to the widget associated with each component and combining the output into the HTML shown earlier.

Figure 1. Generating a HTML table and delegating to other widgets
Document doc = fragment.getOwnerDocument();
    Element table = doc.createElement("table");
    table.setAttribute("class", "sample-container");
    fragment.appendChild(table);

    Element tableBody = doc.createElement("tbody");
    table.appendChild(tableBody);

    Element tableRow = doc.createElement("tr");
    tableBody.appendChild(tableRow);

    Container container = (Container) component;
    for (Component child : container.getComponents()) {
      Element tableCell = doc.createElement("td");
      tableRow.appendChild(tableCell);
      DocumentFragment cellContent
        = doc.createDocumentFragment();
      context.render(child, cellContent,
                     contract.createSubcontract());
      tableCell.appendChild(cellContent);
    }

As in all previous examples, the DOM API is used to generate HTML elements. As shown in the previous section, the component model is represented by a Container, the render method signature requires a Component. As former is a sub-class of the latter, a cast is required to a Container. A for loop is used to iterate over each item in the collection using the getComponents method. Each iteration of the for loop will:

  1. Create a table cell and add it to the table row.
  2. Create a DocumentFragment used when delegating to another widget.
  3. Invoke another widget by calling context.render passing the current component in the collection and the fragment (the third parameter is unused and must always be set as shown above).
  4. Appends the output from the widget to the table cell.

The requirement of this widget was described in the introduction as: "To combine the output of multiple widgets in a horizontal layout". This widget achieves the horizontal layout requirement by generating a HTML table. However, note that it is completely abstracted from the underlying details of the components it is outputting. It is simply iterating over a collection of components and delegating to their associated widgets. In this particular example the components represent a photograph and person details panel. However, without any modification, the widget could display multiple photographs side-by-side if the component model supplied to it was constructed accordingly.