Example: Using HTMLTable classes

The following example shows you how the HTMLTable classes work:

     // Create a default HTMLTable object.
     HTMLTable table = new HTMLTable();

     // Set the table attributes.
     table.setAlignment(HTMLTable.CENTER);
     table.setBorderWidth(1);

     // Create a default HTMLTableCaption object and set the caption text.
     HTMLTableCaption caption = new HTMLTableCaption();
     caption.setElement("Customer Account Balances - January 1, 2000");

     // Set the caption.
     table.setCaption(caption);

     // Create the table headers and add to the table.
     HTMLTableHeader account_header = new HTMLTableHeader(new HTMLText("ACCOUNT"));
     HTMLTableHeader name_header = new HTMLTableHeader(new HTMLText("NAME"));
     HTMLTableHeader balance_header = new HTMLTableHeader(new HTMLText("BALANCE"));

     table.addColumnHeader(account_header);
     table.addColumnHeader(name_header);
     table.addColumnHeader(balance_header);

     // Add rows to the table.  Each customer record represents a row in the table.
     int numCols = 3;
     for (int rowIndex=0; rowIndex< numCustomers; rowIndex++)
     {
        HTMLTableRow row = new HTMLTableRow();
        row.setHorizontalAlignment(HTMLTableRow.CENTER);
   
        HTMLText account = new HTMLText(customers[rowIndex].getAccount());
        HTMLText name = new HTMLText(customers[rowIndex].getName());
        HTMLText balance = new HTMLText(customers[rowIndex].getBalance());

        row.addColumn(new HTMLTableCell(account));
        row.addColumn(new HTMLTableCell(name));
        row.addColumn(new HTMLTableCell(balance));
   
        // Add the row to the table.
        table.addRow(row);
     }
     System.out.println(table.getTag());

The Java™ code example above generates the following HTML code:

     <table align="center" border="1">
     <caption>Customer Account Balances - January 1, 2000</caption>
     <tr>
     <th>ACCOUNT</th>
     <th>NAME</th>
     <th>BALANCE</th>
     </tr>
     <tr align="center">
     <td>0000001</td>
     <td>Customer1</td>
     <td>100.00</td>
     </tr>
     <tr align="center">
     <td>0000002</td>
     <td>Customer2</td>
     <td>200.00</td>
     </tr>
     <tr align="center">
     <td>0000003</td>
     <td>Customer3</td>
     <td>550.00</td>
     </tr>
     </table>

The following table shows how the HTML code above displays in a Web browser.

Table 1. Customer Account Balances - January 1, 2000
ACCOUNT NAME BALANCE
0000001 Customer1 100.00
0000002 Customer2 200.00
0000003 Customer3 550.00