Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in /home/nebupook/public_html/include.database.php on line 2
NebuPookins.net - NP-Complete - How to append text to an EditorPane in Scala
 
How to append text to an EditorPane in Scala

If you google for rich text in Scala, almost invariably you’ll end up hearing about  javax.swing.JEditorPane and its Scala cousin scala.swing.EditorPane. Unfortunately, I couldn’t find any documentation on how to add rich text to this widget. Almost all the tutorials show you how to load a full fledged HTML document from an URL (to the point where it’s obvious that these tutorials are actually just plagiarizing each other), but none of them discuss how to, if your EditorPane already has content, add additional content. Anyway, I figured it out, so I thought I’d share it in case anyone else needs help.

First, define your EditorPane, with a content type of “text/html”, and your base document. I like to use Scala’s built in XML support to generate the HTML (just call .toString at the end, since the API expects a string). I also use the triple-quote trick to include some CSS:

val pane = new EditorPane("text/html",
  <html>
    <head>
      <style type="text/css">{"""
        .header { font-weight: bold}
      """}</style>
    </head>
    <body id="body">
    </body>
  </html>
  .toString)

Then, extract both the document and the “body” HTML element:

val document = pane.peer.getDocument().asInstanceOf[HTMLDocument]
val bodyElement = document.getElement("body") //this method selects HTML elements by id

Finally, call insertAfterEnd() on the document, passing in the body element (or whatever it is you want to append to), again optionally using the native Scala XML syntax:

document.insertBeforeEnd(bodyElement,
  <div class="message">
    <div class="header">{computeHeader()}</div>
    <div class="body">{computeBody()}</div>
  </div>.toString)

Hopefully, this will save someone out there a bit of head-scratching.

 
Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 60

Deprecated: Function ereg_replace() is deprecated in /home/nebupook/public_html/include.parse.php on line 61
E-mail this story to a friend.

You must be logged in to post comments.