Creating a new table

Compared to other table functions, to create a new table and to insert it into a document is a quite simple task. In SimplyHTML this is done with method insertTable of class SHTMLEditorPane (see below). This method is called by a new action of class FrmMain which allows this method to be connected to menus and tool bar buttons, etc.

Method insertTable

Method insertTable builds HTML code for an empty table having one row with a given number of cells. The number of cells to create is passed as a parameter so a calling method can implement a function asking the user for the desired number of table columns.

The generated HTML code then is inserted into the document of the SHTMLEditorPane by inserting it after the current paragraph element using method insertAfterEnd of class HTMLDocument.

Generating HTML with class SHTMLWriter

Package javax.swing.text.html already provides classes to generate HTML for a given Document . Class HTMLWriter of this package is meant for this job with the help of classes AbstractWriter and MinimalHTMLWriter. Unfortunately these classes can not be used in the way it is needed by application SimplyHTML.

In stage 3 of SimplyHTML we already extended HTMLWriter with support to generate SPAN tags for character level attributes. To use the writer in the new context described here, finally it has been reimplemented completely so class SHTMLWriter now is a completely rewritten class not being a subclass of classes of the Swing package of Java anymore.

Reusing methods of SHTMLWriter

As SHTMLWriter writes HTML code to any output writer passed as an argument, we can use it for generating an empty table as well simply by passing a StringWriter as the target for writing. Usually SHTMLWriter produces HTML based on the element structure of a given document. The methods necessary to do so however can be used to generate HTML not related to a document too.

SHTMLWriter provides two methods startTag and endTag which can be used to generate start and end tags as needed. Method startTag accepts a set of attributes too, so start tags can be generated with appropriate HTML and CSS attributes if necessary.

Using SHTMLWriter in method insertTable

To generate HTML for an empty table as described above, SHTMLWriter is instanciated to write to a new StringWriter. Methods startTag and endTag are called for the table, row and cell tags accordingly passing a set of attributes having the applicable table and cell widths. The StringBuffer of StringWriter is converted to a String and inserted into the document finally.