Ejemplo n.º 1
0
  /**
   * Create a table from TableConfig configuration.
   *
   * <p>We create the table using innerHTML instead of creating each DOM node in order to improve
   * the speed. In most of the browsers setting the innerHTML is faster than creating the DOM nodes
   * and appending them.
   *
   * @param doc currently edited document.
   * @param config table configuration (row number, etc).
   * @return the newly created table.
   */
  public Element createTable(Document doc, TableConfig config) {
    StringBuffer table = new StringBuffer("<table>");

    StringBuffer row = new StringBuffer("<tr>");
    for (int i = 0; i < config.getColNumber(); i++) {
      row.append("<td>");
      // The default cell content depends on the browser. In Firefox the best option is to use a BR.
      // Firefox
      // itself uses BRs in order to allow the user to place the caret inside empty block elements.
      // In Internet
      // Explorer the best option is to set the inner HTML of each cell to the empty string, after
      // creation. For
      // now lets keep the non-breaking space. At some point we should have browser specific
      // implementations for
      // FF and IE. Each will overwrite this method and add specific initialization.
      row.append(TableUtils.CELL_DEFAULTHTML);
      row.append("</td>");
    }
    row.append("</tr>");

    if (config.hasHeader()) {
      table.append("<thead>");
      if (config.getRowNumber() > 0) {
        table.append(row.toString().replace("td", "th"));
      }
      table.append("</thead>");
    }

    table.append("<tbody>");
    for (int i = config.hasHeader() ? 1 : 0; i < config.getRowNumber(); i++) {
      table.append(row.toString());
    }
    table.append("</tbody></table>");

    Element container = doc.createDivElement().cast();
    container.setInnerHTML(table.toString());
    Element tableElement = (Element) container.getFirstChild();
    container.removeChild(tableElement);
    return tableElement;
  }
Ejemplo n.º 2
0
  /**
   * Insert a HTML table in the editor.
   *
   * @param config creation parameters.
   */
  public void insertTable(TableConfig config) {
    Element table = createTable(rta.getDocument(), config);
    insertBlockHTMLExecutable.execute(table);

    // Place the caret at the beginning of the first cell.
    Range range = rta.getDocument().createRange();
    range.selectNodeContents(
        domUtils.getFirstDescendant(
            table, config.hasHeader() ? TableUtils.COL_HNODENAME : TableUtils.COL_NODENAME));
    range.collapse(true);

    Selection selection = rta.getDocument().getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  }