jsjavacomm example — DOM Modification

When this page loads you should see a Java applet below which you can use to add paragraphs to this document.

Paragraphs added by the Java applet should appear below

Source code

domModification.html

The object element of this page which loads the applet looks like this:

<object id="domModificationApplet" name="domModificationApplet" type="application/x-java-applet"
	archive="jsjavacomm-0.1-SNAPSHOT-tests.jar,jsjavacomm-0.1-SNAPSHOT.jar"
	code="net.sourceforge.jsjavacomm.examples.DOMModification"
	width="300" height="400">
	<param name="mayscript" value="true" />
</object>

DOMModification.java

Here's the essentials of what the java applet code looks like:

public class DOMModification extends JSApplet implements ActionListener {

	/** 
	 * The text pane for this applet.
	 */
	private JEditorPane jep;
		
	/**
	 * The document which is currently being displayed by the browser. 
	 */
	private Document doc;
	
	/**
	 * Initialises the Java components.
	 */
	@Override
	public void init() {
		super.init();
	
		JButton jbut = new JButton("Add paragraph");
		jbut.addActionListener(this);
		
		jep = new JEditorPane("text/plain",
				"This paragraph of text can be added to the document by pressing the 'Add paragraph' button.");		
		
		getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
		getContentPane().add(jbut);
		getContentPane().add(jep);						
	}
	
	/**
	 * Gets the document which is currently being displayed by the browser.
	 */
	@Override
	public void start() {
		JSDOMImplementation domImpl = new JSDOMImplementationImpl();
		JSWindow window = domImpl.getWindow(this);
		doc = window.getDocument();
	}
	
	/**
	 * Called when the user presses the button. Creates a new Text node,
	 * wraps it in a p element and adds it to the document as a child
	 * of the element who's id is "container".
	 */
	public void actionPerformed(ActionEvent e) {		
		Text newText = doc.createTextNode(jep.getText());
		Element newParagraph = doc.createElement("p");
		newParagraph.appendChild(newText);
		
		Element container = doc.getElementById("container");
		container.appendChild(newParagraph);
	}
}