HTMLDocument problems

When I select a pice of text and click on "Format" then there are more characters formatted then there have been selected. Why?
And when I click on "Save" with just using the text that appears when starting the program then this text is not outputted to HTML. Why is that?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.html.CSS;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
public class AdditionalText extends JFrame implements ActionListener {
     private static final int FRAME_WIDTH = 640;
     private static final int FRAME_HEIGHT = 480;
     private static final String FONT_FAMILY = "Courier New";
     private static final String FONT_SIZE = "24";
     private JButton leftAlign;
     private JButton centerAlign;
     private JButton rightAlign;
     private JTextPane editor;
     private JButton save;
     private JButton dump;
     private JButton format;
     public AdditionalText() {
          setTitle("Test Frame");
          JPanel topToolbar = new JPanel();
          leftAlign = new JButton("Left");
          centerAlign = new JButton("Center");
          rightAlign = new JButton("Right");
          ActionListener alignLeft = new HTMLEditorKit.AlignmentAction("alignLeft", 0);
          ActionListener alignCenter = new HTMLEditorKit.AlignmentAction("alignCenter", 1);
          ActionListener alignRight = new HTMLEditorKit.AlignmentAction("alignRight", 2);
          leftAlign.addActionListener(alignLeft);
          centerAlign.addActionListener(alignCenter);
          rightAlign.addActionListener(alignRight);
          topToolbar.add(leftAlign);
          topToolbar.add(centerAlign);
          topToolbar.add(rightAlign);
          editor = createEditor();
          JPanel bottomToolbar = new JPanel();
          save = new JButton("Save");
          save.addActionListener(this);
          dump = new JButton("Dump");
          dump.addActionListener(this);
          format = new JButton("Format");
          format.addActionListener(this);
          bottomToolbar.add(save);
          bottomToolbar.add(dump);
          bottomToolbar.add(format);
          getContentPane().add(BorderLayout.NORTH, topToolbar);
          getContentPane().add(BorderLayout.CENTER, editor);
          getContentPane().add(BorderLayout.SOUTH, bottomToolbar);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          setSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
          setLocation((screenSize.width - FRAME_WIDTH) / 2, (screenSize.height - FRAME_HEIGHT) / 2);
     private JTextPane createEditor() {
          JTextPane editor = new JTextPane() {
               public void paintComponent(Graphics g) {
                    Graphics2D g2 = (Graphics2D) g;
                    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                    super.paintComponent(g2);
          editor.setEditorKit(new HTMLEditorKit());
          HTMLDocument htmlDocument = (HTMLDocument) editor.getDocument();
          MutableAttributeSet attr = new SimpleAttributeSet();
          StyleSheet ss = htmlDocument.getStyleSheet();
          ss.addCSSAttribute(attr, CSS.Attribute.FONT_FAMILY, FONT_FAMILY);
          ss.addCSSAttribute(attr, CSS.Attribute.FONT_SIZE, FONT_SIZE);
          editor.setCharacterAttributes(attr, false);
          try {
               htmlDocument.insertString(0, "Sample Text 123 ����", attr);
          } catch (BadLocationException e) {
               e.printStackTrace();
          return editor;
     public void actionPerformed(ActionEvent e) {
          HTMLDocument htmlDocument = (HTMLDocument) editor.getDocument();
          if(e.getSource() == save) {
               HTMLEditorKit kit = (HTMLEditorKit)editor.getEditorKitForContentType("text/html");
               try {
                    kit.write(System.out, htmlDocument, 0, htmlDocument.getLength());
               } catch (IOException ex) {
                    ex.printStackTrace();
               } catch (BadLocationException ex) {
                    ex.printStackTrace();
          } else if(e.getSource() == dump) {
               htmlDocument.dump(System.err);
          } else if(e.getSource() == format) {
               HTMLDocument doc = (HTMLDocument) editor.getDocument();
               MutableAttributeSet attr = new SimpleAttributeSet();
               StyleSheet ss = htmlDocument.getStyleSheet();
               ss.addCSSAttribute(attr, CSS.Attribute.FONT_WEIGHT, "bold");
               ss.addCSSAttribute(attr, CSS.Attribute.COLOR, "red");
               int start = editor.getSelectionStart();
               int end = editor.getSelectionEnd();
               System.out.println("Start: " + start + "\tEnd: " + end);
               doc.setCharacterAttributes(start, end, attr, false);
     public static void main(String[] args) {
          try {
               UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          } catch (ClassNotFoundException e) {
               e.printStackTrace();
          } catch (InstantiationException e) {
               e.printStackTrace();
          } catch (IllegalAccessException e) {
               e.printStackTrace();
          } catch (UnsupportedLookAndFeelException e) {
               e.printStackTrace();
          AdditionalText at = new AdditionalText();
          at.show();
}

Forget about the other question. I solved it in another thread.
This is now a very simple HTML editor which works (if someone is interested in it):
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.UIManager;
import javax.swing.text.AttributeSet;
import javax.swing.text.Element;
import javax.swing.text.MutableAttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.html.CSS;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
* Created on 13.04.2003
* @author anonymous
* @version 0.0.1
* This is a very simple HTML Editor.
* It's purpose is to enter text and format it, if needed.
* The editor supports exporting the text to HTML.
public class AdditionalText extends JFrame implements ActionListener {
     private static final int FRAME_WIDTH = 640;
     private static final int FRAME_HEIGHT = 480;
     private static final String FONT_FAMILY = "body {font-size: 18;}";
     private static final String FONT_SIZE = "body {font-family: monospaced;}";
     private static final String SAMPLE_TEXT = "sample Text 123 ����";
     private JTextPane editor;
     private JButton save;
     private JButton dump;
     private JButton formatText;
     private JButton clearFormatting;
      * Constructor for the <code>AdditionalText</code> editor.
      * Most GUI components are defined, initialized and assembled here.
     public AdditionalText() {
          setTitle("HTML Editor Demo");
          // Assemble the top toolbar:
          JPanel topToolbar = new JPanel();
          topToolbar.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 10));
          JButton leftAlign = new JButton("Left");
          JButton centerAlign = new JButton("Center");
          JButton rightAlign = new JButton("Right");
          leftAlign.addActionListener(new HTMLEditorKit.AlignmentAction(null, 0));
          centerAlign.addActionListener(new HTMLEditorKit.AlignmentAction(null, 1));
          rightAlign.addActionListener(new HTMLEditorKit.AlignmentAction(null, 2));
          formatText = new JButton("Format Text");
          formatText.addActionListener(this);
          clearFormatting = new JButton("Clear Formatting");
          clearFormatting.addActionListener(this);
          topToolbar.add(leftAlign);
          topToolbar.add(centerAlign);
          topToolbar.add(rightAlign);
          topToolbar.add(formatText);
          topToolbar.add(clearFormatting);
          // Assemble the editor:
          editor = createEditor();
          JScrollPane editorScrollPane = new JScrollPane(editor);
          // Assemble the bottom toolbar:
          JPanel bottomToolbar = new JPanel();
          bottomToolbar.setLayout(new FlowLayout(FlowLayout.CENTER, 50, 10));
          save = new JButton("Save");
          save.addActionListener(this);
          dump = new JButton("Dump");
          dump.addActionListener(this);
          bottomToolbar.add(save);
          bottomToolbar.add(dump);
          // Add all the JPanels to the JFrame:
          Container container = getContentPane();
          container.add(BorderLayout.NORTH, topToolbar);
          container.add(BorderLayout.CENTER, editorScrollPane);
          container.add(BorderLayout.SOUTH, bottomToolbar);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          // Display the window on the center of the screen:
          Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
          setSize(new Dimension(FRAME_WIDTH, FRAME_HEIGHT));
          setLocation((screenSize.width - FRAME_WIDTH) / 2, (screenSize.height - FRAME_HEIGHT) / 2);
      * Creation and set up of an simple HTML editor.
      * @return the created editor.
     private JTextPane createEditor() {
          JTextPane editor = new JTextPane() {
               // Improve readability of the text inside the editor:
               public void paintComponent(Graphics g) {
                    Graphics2D g2 = (Graphics2D) g;
                    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                                             RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                    super.paintComponent(g2);
          editor.setEditorKit(new SHTMLEditorKit());
          // Set the default style for the document:
          HTMLDocument htmlDocument = (HTMLDocument)editor.getDocument();
          MutableAttributeSet mutuableAttributeSet = new SimpleAttributeSet();
          StyleSheet styleSheet = htmlDocument.getStyleSheet();
          styleSheet.addRule(FONT_FAMILY);
          styleSheet.addRule(FONT_SIZE);
          // Insert a sample text into the editor for testing purpose:
          try {
               Element root = htmlDocument.getDefaultRootElement();
               Element element = root.getElement(0).getElement(0);
               htmlDocument.insertAfterEnd(element, "<p>" + SAMPLE_TEXT + "</p>");
          } catch (Exception e) {
               e.printStackTrace();
          return editor;
      * Handling the actions associated to the buttons "Save", "Dump", "Format Text"
      * and "Clear Formatting".
      * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
     public void actionPerformed(ActionEvent e) {
          HTMLDocument htmlDocument = (HTMLDocument) editor.getDocument();
          if (e.getSource() == save) {
               HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKitForContentType("text/html");
               try {
                    // Output the document object to HTML text:
                    kit.write(System.out, htmlDocument, 0, htmlDocument.getLength());
               } catch (Exception ex) {
                    ex.printStackTrace();
          } else if (e.getSource() == dump) {
               // Output the document object to a XML like text representation:
               htmlDocument.dump(System.err);
          } else if (e.getSource() == formatText) {
               // Apply formatting to the selected text:
               int start = editor.getSelectionStart();
               int end = editor.getSelectionEnd();
               MutableAttributeSet attr = new SimpleAttributeSet();
               StyleSheet ss = htmlDocument.getStyleSheet();
               ss.addCSSAttribute(attr, CSS.Attribute.FONT_WEIGHT, "bold");
               ss.addCSSAttribute(attr, CSS.Attribute.COLOR, "blue");
               htmlDocument.setCharacterAttributes(start, end - start, attr, false);
          } else if (e.getSource() == clearFormatting) {
               // Remove formatting of the selected text:
               int start = editor.getSelectionStart();
               int end = editor.getSelectionEnd();
               Element element = htmlDocument.getCharacterElement(start);
               AttributeSet attributeSet = element.getAttributes();
               StyleSheet styleSheet = htmlDocument.getStyleSheet();
               attributeSet = styleSheet.removeAttribute(attributeSet, CSS.Attribute.FONT_WEIGHT);
               attributeSet = styleSheet.removeAttribute(attributeSet, CSS.Attribute.COLOR);
               htmlDocument.setCharacterAttributes(start, end - start, attributeSet, true);
      * Method for executing the <code>AdditionalText</code> editor.
      * @param args no arguments needed
      * @throws Exception thrown if the system look & feel can't be set
     public static void main(String[] args) throws Exception {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          AdditionalText at = new AdditionalText();
          at.show();
          while(!at.editor.requestFocusInWindow());
          at.editor.setCaretPosition(AdditionalText.SAMPLE_TEXT.length());
}

Similar Messages

  • Insert BASE tag into HTMLDocument problem

    Hi,
    I've made a prog that read the HTML content from an URL, and write it into a file. But before writing it, I'd like to change the content to add <BASE href="http://www.site.com"></BASE> into the head part of the HTMLDocument. In my prog, I've made a insertBeforeEnd(...) to insert the <BASE> tag, but it's not inserted. I've made another insertBeforeEnd(...) to insert "hello world" (just for test) and it's inserted into the HTMLDocument. Can someone help me ? thanks a lot.
    My prog :
    import java.io.*;
    import java.net.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    public class InsertIntoHTML {
       public static void main(String[] args) {
          URL                  url = null;
          HttpURLConnection      conn;
          HTMLEditorKit         htmlKit;
          HTMLDocument         htmlDoc;
          InputStream            in;
          Element               head;
          boolean               ignoreCharSet = true;
          htmlKit = new HTMLEditorKit();
          htmlDoc = new HTMLDocument();
          try {
             url = new URL("http://www.google.com/");
          catch (java.net.MalformedURLException e) {}
          htmlDoc.putProperty(Document.StreamDescriptionProperty, url);
          htmlDoc.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
          // read www.yahoo.com into HTML document
          try {
             conn = (HttpURLConnection) url.openConnection();
             in = conn.getInputStream();
             Reader reader = new InputStreamReader(in);
             Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator");
             HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance();
             htmlDoc.setParser(parser);
             HTMLEditorKit.ParserCallback htmlReader = htmlDoc.getReader(0);
             parser.parse(reader, htmlReader, ignoreCharSet);
             htmlReader.flush();
          catch (javax.swing.text.BadLocationException ex) {}
          catch (java.lang.ClassNotFoundException e) {}
          catch (java.lang.InstantiationException e) {}
          catch (java.lang.IllegalAccessException e) {}
          catch (java.io.IOException e) {}
          htmlDoc.setBase(url);
          // find <HEAD> tag into HTML document
          head = getHeadElement(htmlDoc);
          try {
             // insert <BASE> tag into <HEAD> element
             htmlDoc.insertBeforeEnd(head, "<BASE href=\"http://www.google.com/\"></BASE>");
             htmlDoc.insertBeforeEnd(head, "Hello world !");
          catch (javax.swing.text.BadLocationException e) {}
          catch (java.io.IOException e) {}
          // write HTML document into file named yahoo.html      
          try {
             htmlKit.write(new FileOutputStream(new File("google.html")), htmlDoc, 0, htmlDoc.getLength());
          catch (java.io.FileNotFoundException e) {}
          catch (java.io.IOException e) {}
          catch (javax.swing.text.BadLocationException e) {}
       // Find first element into HTML document equals to tag parameter
       public synchronized static final Element findElement(Element root, HTML.Tag kind) {
          if(root == null) return(null);
          if(matchElementType(root, kind)) {
             return(root);
          int count = root.getElementCount();
          if(count > 0) {
             for(int i = 0 ; i<count ; i++) {
                Element child = root.getElement(i);
                Element e = findElement(child, kind);
                if(e != null)
                   return(e);
       return(null);
       public synchronized static final boolean matchElementType(Element e, HTML.Tag kind) {
          return(e.getAttributes().getAttribute(StyleConstants.NameAttribute) == kind);
       // Find HEAD element into HTML document
       public synchronized static final Element getHeadElement(HTMLDocument doc) {
          return(findElement(doc.getRootElements()[0], HTML.Tag.HEAD));

    first, thanks dvorhra09 for your help. unfortunately, if I use &lt; and &gt; instead of '<' and '>', the <BASE> tag is no more interpreted by my browser when the file is loaded, and the <BASE> tag is displayed textually. below, is what I tested :
    htmlDoc.insertBeforeEnd(head, "&lt;BASE href=\"http://www.google.com/\"&gt;&lt;/BASE&gt;");

  • Problem with jsp and controller

    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt"%>
    <%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
    <%@ page import='com.uk.nhs.training.data.ActivityMatrix'%>
    <SCRIPT language="JavaScript" type="text/javascript">
    function bookActivity()
    if (document.bookActivityController.activitySelect.selectedIndex == 0)
    alert("Please Select Activity");
    else if (document.bookActivityController.trainerId.selectedIndex == 0)
    alert ( "Please Select Trainer");
    else if(document.bookActivityController.fromDate.value=="")
    alert("Please supply the Start Date of Activity")
    else
    validateForExistingCourses();
    function validateForExistingCourses()
    flag="wait";
    var trainerId=document.getElementById("trainerId").value;
    var fromDate=document.getElementById("fromDate").value;
    var toDate=document.getElementById("toDate").value;
    var activityId=document.getElementById("activitySelect").value;
    url="ajaxList.htm?actionType=checkBookedCoursesActivities&trainerId="+trainerId+"&fromDate="+fromDate+"&toDate="+toDate+"&activitySelect="+activityId;
    what = "checkForPreBookedCoursesActivities(req.responseXML)";
    doCallback(null);
    function checkForPreBookedCoursesActivities(theXmlResponse)
    // alert("in here in checking prebookedCourses");
    if(theXmlResponse != null)
         var isActivityExisting = theXmlResponse.getElementsByTagName('existingActivity')[0].text;
         var isCourseExisting = theXmlResponse.getElementsByTagName('existingbookedcourse')[0].text;     
              if(isActivityExisting=="Y")
              alert("Activity You are trying to book for Trainer already exists");
              return false;
              else if(isCourseExisting=="Y")
              if(confirm('Conflict Message. The dates choosen conflict with a current booking. Do you want to override'))
    window.open("/training1.1/secure/prebookedEvents.htm","clientwindow",'StatusBar', 'toolbar=yes,resizable=yes,scrollbars=yes,width=500,height=400,left=0,top=0');
    return false;
    else
    document.bookActivityController.action="/training1.1/secure/bookActivityTrainer.htm?actionType=submitForm";
    document.bookActivityController.submit();
    function goHomePage()
         window.location="/training1.1/secure/welcome.htm";
    function showHideAmPm(divId)
    if(document.bookActivityController.halfday.checked==true)
    showDiv(divId);
    else
    hideDiv(divId);
    function showDiv(divId)
    var item = document.getElementById(divId);
    alert("show item"+item);
    if (item)
    item.className='unhidden';
    function hideDiv(divId)
    var item = document.getElementById(divId);
    alert("unhide item"+item);
    if (item)
    item.className='hidden';
    function getActivitiesPm()
    if(document.bookActivityController.am.checked==true)
    document.bookActivityController.pm.checked=false;
    flag="wait";
         url="ajaxList.htm?actionType=activities&keyword=PM";
         what = "setActivities(req.responseXML)";
         doCallback(null);
         document.bookActivityController.activityTimeSelect.value="halfday";
         document.bookActivityController.activityTimeSubType.value="pm";
         // alert("subType"+document.bookActivityController.activityTimeSubType.value);
    function getActivitiesAm()
    if(document.bookActivityController.pm.checked==true)
    document.bookActivityController.am.checked=false;
    flag="wait";
         url="ajaxList.htm?actionType=activities&keyword=AM";
         what = "setActivities(req.responseXML)";
         doCallback(null);
         document.bookActivityController.activityTimeSelect.value="halfday";
         document.bookActivityController.activityTimeSubType.value="pm";
    function getSingleDayActivities()
    if(document.bookActivityController.singleday.checked==true)
    document.bookActivityController.moredays.checked=false;
    document.bookActivityController.halfday.checked=false;
    hideDiv('partofhalfday');
    document.bookActivityController.activityTimeSelect.value="fullday";
    flag="wait";
         url="ajaxList.htm?actionType=activities&keyword=FullDay";
         what = "setActivities(req.responseXML)";
         doCallback(null);
    else
    hideDiv('activitySelect');
    function getMoreDaysActivities()
    alert();
    if(document.bookActivityController.moredays.checked==true)
    document.bookActivityController.singleday.checked=false;
    document.bookActivityController.halfday.checked=false;
    hideDiv('partofhalfday');
    document.bookActivityController.activityTimeSelect.value="moredays";
    flag="wait";
         url="ajaxList.htm?actionType=activities&keyword=FullDay";
         what = "setActivities(req.responseXML)";
         doCallback(null);
    else
    hideDiv('activitySelect');
    showDiv('dateTo');
    function setActivities(theXmlResponse)
              //start filling the Venues Select boxes now
              if(theXmlResponse != null)
                   var coursesBox=document.getElementById("activitySelect");
                   coursesBox.options.length=0;
                   var activityElementsLength=theXmlResponse.getElementsByTagName('activity').length;     
                   var activityElementsArray=theXmlResponse.getElementsByTagName('activity');
                   //alert("length"+activityElementsLength+activityElementsArray);                              
              for(x = 0; x < activityElementsLength; x++)
                        //coursesBox.options[coursesBox.options.length] = new Option(coursesElementsArray[x].firstChild.text, coursesElementsArray[x].lastChild.text);
                        var optn = document.createElement("OPTION");
                   optn.text = activityElementsArray[x].firstChild.text;
    optn.value = activityElementsArray[x].lastChild.text;
    coursesBox.options.add(optn);
         if (activityElementsLength>0)
                   showDiv('activityTD');
              flag="release";
    </script>
    <div id="content"><!-- Top story -->
    <div id="topstory" class="box">
    <div id="topstory-img"></div>
    <!-- /topstory-img -->
    <div id="topstory-desc">
    <div id="topstory-title"><strong>BOOK Activity</strong></div>
    <!-- /topstory-title -->
    <div id="topstory-desc-in"></div>
    <!-- /topstory-desc-in --></div>
    <!-- /topstory-desc --></div>
    <!-- /topstory -->
    <div id="bodycontent">
    <% int errorCount=0; %>          
              <spring:bind path="bookactivityevent.*">
              <c:forEach items="${status.errorMessages}" var="error">
                        <B><font color="red">Error: <c:out value="${error}"/></font><B/>
                        <% errorCount++; %>
              </c:forEach>
              </spring:bind>
    <form method="post" name="bookActivityController" action="<c:url value="/secure/bookActivityTrainer.htm"/>">
    <table align="right" width="50%" border=0>
    <input type="hidden" name="activityTimeSelect"/>
    <input type="hidden" name="activityTimeSubType"/>
    <tr>
    <td align="left">
    <INPUT TYPE="checkbox" NAME="halfday" onclick="showHideAmPm('partofhalfday')">Half Day    
    <div align="left "id="partofhalfday" class="hidden">
    <INPUT TYPE="RADIO" NAME="am" onClick="getActivitiesAm()" value="am">AM <INPUT TYPE="RADIO" NAME="pm" onClick="getActivitiesPm()">PM <BR>
    </div>
    </td>
    </tr>
    <tr><td><INPUT TYPE="checkbox" NAME="singleday" onClick="getSingleDayActivities()"> Single Day</td>
    </tr>
    <tr>
    <td><INPUT TYPE="checkbox" NAME="moredays" onClick="getMoreDaysActivities()"> More Days</td>
    </tr>
         <tr>
              <td align="left" id="activityTD">Activity :
              <c:set var="activityMap" value=${requestScope.activityMap}/>
         <c:choose>
                        <c:when test="${activityMap = null}"
         <spring:bind path="bookactivityevent.userSuppliedActivity.activity.activityId">
              <select name="activitySelect" id="activitySelect" size="1"
                   STYLE="width: 150px">
                   <option value="Choose Activity" default>Choose Activity</option>
              </select>
              </spring:bind>
              </c:when>
              <c:otherwise>      
              <spring:bind path="bookactivityevent.userSuppliedActivity.activity.activityId">
              <select name="activitySelect" id="activitySelect"
                   size="1" STYLE="width: 150px">
                   <option value="" default>Choose Activity</option>
                   <c:forEach var="activity" items="${activityMap}" varStatus="a">
                        <c:choose>
                             <c:when
                                  test="${(bookactivityevent !=null) && (bookactivityevent.userSuppliedActivity.activity.activityId == activity.activityId)}">
                                  <option value="<c:out value="${activity.activityId}"/>" selected><c:out
                                       value="${activity.activityId}" /></option>
                             </c:when>
                             <c:otherwise>
                             <option value="<c:out value="${activity.activityId}"/>"><c:out
                                       value="${activity.activity}"/>
                             </c:otherwise>
                        </c:choose>
                   </c:forEach>
              </select>
         </spring:bind>
         </c:otherwise>
         </c:choose>
         </td>
    </tr>
         <tr>
              <td align="left">Trainer:
              <spring:bind path="bookactivityevent.userSuppliedActivity.trainer.trainerId">
              <select name="trainerId" id="trainerId"
                   size="1" STYLE="width: 150px">
                   <option value="" default>Choose Trainer</option>
                   <c:forEach var="trainer" items="${trainers}" varStatus="a">
                        <c:choose>
                             <c:when
                                  test="${(bookactivityevent !=null) && (bookactivityevent.userSuppliedActivity.trainer.trainerId == trainer.trainerId)}">
                                  <option value="<c:out value="${trainer.trainerId}"/>" selected>
                                  <c:out value="${trainer.firstName}"/>&nbsp<c:out
                                       value="${trainer.surName}" /></option>
                             </c:when>
                             <c:otherwise>
                                  <option value="<c:out value="${trainer.trainerId}"/>"><c:out
                                       value="${trainer.firstName}"/>&nbsp<c:out
                                       value="${trainer.surName}" /></option>
                             </c:otherwise>
                        </c:choose>
                   </c:forEach>
              </select>
         </spring:bind>     
              </td>
         </tr>
         <tr>
              <td align="left" id="dateFrom">From Date
              <spring:bind path="bookactivityevent.userSuppliedActivity.dateFrom">
              <input type="text" name="dateFrom" value=""/>
              </spring:bind>
              <img
                   src="../design/cal.gif" width="16" height="16" border="0"
                   alt="Click Here to Pick up the date"></td>
         </tr>
         <tr>
              <td align="left" id="dateTo" class="hidden">To Date
              <spring:bind path="bookactivityevent.userSuppliedActivity.dateTo">
              <input type="text" name="dateTo" value=""/>
              </spring:bind>
              <img
                   src="../design/cal.gif" width="16" height="16" border="0"
                   alt="Click Here to Pick up the date"></td>
         </tr>
         <tr>
              <td align="left" colspan="2"><input type="submit" name="_target1" value="BookActivity"/></td>
                   <c:if test="${(bookactivityevent != null) && (not empty bookactivityevent.conflictBookings)}">
    <td align="left" colspan="2"><input type="submit" name="_target2" value="OverRideBookings"/></td>
    </c:if>
              <td align="left" colspan="2"><input type="button" name="Cancel"
                   value="Cancel" onClick="goHomePage();" /></td>
         </tr>
    </table>
    </form>
    </div>
    <hr class="noscreen"/>
    <div class="content-padding"></div>
    <script language="JavaScript">
         var cal1 = new calendar1(document.bookActivityController.elements['dateFrom']);
         cal1.year_scroll = true;
         cal1.time_comp = false;
    var cal2 = new calendar1(document.bookActivityController.elements['dateTo']);
         cal2.year_scroll = true;
         cal2.time_comp = false;
    </script></div>
    <!-- /content -->
    package com.uk.nhs.training.controller;
    import java.beans.PropertyEditorSupport;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.swing.text.html.HTMLDocument;
    import org.apache.commons.logging.Log;
    import org.apache.commons.logging.LogFactory;
    import org.springframework.util.StringUtils;
    import org.springframework.validation.BindException;
    import org.springframework.validation.Errors;
    import org.springframework.validation.ValidationUtils;
    import org.springframework.web.bind.ServletRequestDataBinder;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.AbstractWizardFormController;
    import org.springframework.web.servlet.view.RedirectView;
    import com.uk.nhs.training.contractUtility.ContractHtmlReader;
    import com.uk.nhs.training.data.Activity;
    import com.uk.nhs.training.data.ActivityMatrix;
    import com.uk.nhs.training.data.BookActivityEvent;
    import com.uk.nhs.training.data.Booking;
    import com.uk.nhs.training.data.BookingDetails;
    import com.uk.nhs.training.data.Client;
    import com.uk.nhs.training.data.Course;
    import com.uk.nhs.training.data.Trainer;
    import com.uk.nhs.training.data.Venue;
    import com.uk.nhs.training.data.ActivityTimeConstants;
    import com.uk.nhs.training.service.ActivityMatrixService;
    import com.uk.nhs.training.service.ActivityService;
    import com.uk.nhs.training.service.BookingDetailsService;
    import com.uk.nhs.training.service.BookingService;
    import com.uk.nhs.training.service.ClientService;
    import com.uk.nhs.training.service.CourseService;
    import com.uk.nhs.training.service.TrainersService;
    import com.uk.nhs.training.service.VenueService;
    public class BookActivityController extends AbstractWizardFormController {
         protected final Log logger = LogFactory.getLog(getClass());
         private BookingService bookingFacade;
         private BookingDetailsService bookingDetailsFacade;
         private CourseService courseFacade;
         private VenueService venueFacade;
         private ClientService clientFacade;
         private ActivityMatrixService activityMatrixFacade;
         private ActivityService activityFacade;
         private TrainersService trainersFacade;
         private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
         public BookActivityController() {
              setCommandClass(BookActivityEvent.class);
         setCommandName("bookactivityevent");
         setBindOnNewForm(true);
         protected Object formBackingObject(HttpServletRequest request)
                   throws Exception {
              BookActivityEvent bookActivityEvent = new BookActivityEvent();
              ActivityMatrix activityMatrix = new ActivityMatrix();
              activityMatrix.setActivity(new Activity());
              activityMatrix.setTrainer(new Trainer());
              List<Booking> bookingList = new ArrayList<Booking>();
              bookActivityEvent.setUserSuppliedActivity(activityMatrix);
              bookActivityEvent.setConflictBookings(bookingList);
              return bookActivityEvent;
         public Map referenceData(HttpServletRequest request, Object command, Errors errors, int Page)
              List trainers = trainersFacade.loadTrainers();
         Map trainersActivitiesMap = new HashMap();
              trainersActivitiesMap.put("trainers", trainers);          
              return trainersActivitiesMap;
         protected ModelAndView processFinish(HttpServletRequest request,
                   HttpServletResponse response, Object command, BindException errors) {
              try {
                   ActivityMatrix activity = (ActivityMatrix) command;
                   activityMatrixFacade.saveActivityMatrix(activity);
                   logger.info("Activity is successfully saved for the trainer");
              } catch (Exception e) {
                   e.getClass();
                   e.printStackTrace();
              return new ModelAndView("bookSuccess");
         @Override
         protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
              dateFormat.setLenient(true);
              binder.registerCustomEditor(java.sql.Date.class, "dateFrom", new SqlDateEditor(true));
              binder.registerCustomEditor(java.sql.Date.class, "dateTo", new SqlDateEditor(false));
              binder.registerCustomEditor(java.sql.Date.class, null, new SqlDateEditor(true));
         protected ModelAndView handleInvalidSubmit(HttpServletRequest request,
                   HttpServletResponse response) throws Exception {
              return new ModelAndView("bookInvalidSubmit");
         @Override
         protected ModelAndView processCancel(HttpServletRequest request,
                   HttpServletResponse response, Object command, BindException errors)
                   throws Exception {
              return new ModelAndView(new RedirectView("welcome.htm"));
         @Override
         protected void onBindAndValidate(HttpServletRequest request,
                   Object command, BindException errors, int page) throws Exception {
              BookActivityEvent bookActivityEvent = (BookActivityEvent) command;
              System.out.println(" PAGE : " + page);
              try {
                   switch (page) {
                   case 0:
                        if (request.getParameter("_target1") != null) {
                             ActivityMatrix userActivityMatrix = bookActivityEvent.getUserSuppliedActivity();
                             buildActivityMatrix(request, bookActivityEvent);     
                             validateActivityMatrix(bookActivityEvent, errors);
                             if (errors.getErrorCount() == 0)
                                  Trainer trainer = (Trainer) trainersFacade.loadTrainersById(userActivityMatrix.getTrainer().getTrainerId());
                                  bookActivityEvent.getUserSuppliedActivity().setTrainer(trainer);
                                  Activity activity= (Activity) activityFacade.loadActivitiesById(userActivityMatrix.getActivity().getActivityId());
                                  bookActivityEvent.getUserSuppliedActivity().setActivity(activity);
                                  boolean activityExists = checkForExistingActivities(userActivityMatrix, errors);
                                  if(!activityExists)
                                  boolean bookingsExist =      checkForBookedCourses(request, bookActivityEvent, errors);
                                  if(bookingsExist)
                                       // inject an error code so that it can be used in GUI
                                       errors.rejectValue("dateFrom","invalid dates","Trainer has Bookings in conflict with the Supplied Activity Dates");
                                  else
                                       errors.rejectValue("dateFrom","Activity Dates supplied already exist");
                        break;
                   case 1:
                        if (request.getParameter("_target2") != null)
                             * Get the user supplied activitymatrix and try to get all the bookings which are in conflict for the trainer
                        List<Booking> conflictBookingsList = (List<Booking>)request.getSession().getAttribute("conflictBookingsList");
                        break;
                   default:
              } catch (Exception e) {
                   System.err.println("Exception :" + e.getMessage());
              super.onBindAndValidate(request, command, errors, page);
         * @param request
         * @param userActivity
         * @param bookActivityEvent TODO
         private ActivityMatrix buildActivityMatrix(HttpServletRequest request, BookActivityEvent bookActivityEvent) {
              ActivityMatrix userActivity = bookActivityEvent.getUserSuppliedActivity();
              userActivity.getTrainer().setTrainerId((String)(request.getParameter("trainerId")));
              userActivity.getActivity().setActivityId((String)(request.getParameter("activitySelect")));          
              String activityTime = (String)request.getParameter("activityTimeSelect");
              String activitySubType = (String)request.getParameter("activityTimeSubType");
              if("fullday".equals(activityTime))
                   userActivity.getActivity().setTime(ActivityTimeConstants.FULLDAY.toString());
              else if("moredays".equals(activityTime))
                   userActivity.getActivity().setTime(ActivityTimeConstants.MOREDAYS.toString());
              else if("halfday".equals(activityTime)&& "am".equals(activitySubType))
                   userActivity.getActivity().setTime(ActivityTimeConstants.AM.toString());               
              else if("halfday".equals(activityTime)&& "pm".equals(activitySubType))
                   userActivity.getActivity().setTime(ActivityTimeConstants.PM.toString());
              if(!("moredays".equals(activityTime)))
                   userActivity.setDateTo(bookActivityEvent.getDateFrom());
              userActivity.setDateFrom(bookActivityEvent.getDateFrom());
              bookActivityEvent.setUserSuppliedActivity(userActivity);
              return userActivity;
         * Create an empty Booking details for client and course...
         * @param booking
         private void setInitialBookingDetails(Booking booking, BindException errors) {
              if (booking.getBookingType().equals("Client-Based")) {
                   if (booking.getClient() == null
                             || booking.getClient().getClientId() == null) {
                        booking.setClient(new Client());
              } else if (booking.getBookingType().equals("Staff")) {
                   booking.setClient(null);
              if (booking.getBookingDetails() == null) {
                   List<BookingDetails> bkDetailsList = new ArrayList<BookingDetails>();
                   BookingDetails bkDetails = new BookingDetails();
                   bkDetails.setCourse(new Course());
                   bkDetailsList.add(bkDetails);
                   booking.setBookingDetails(bkDetailsList);
              } else {
                   List bkDetList = booking.getBookingDetails();
                   if (bkDetList.size() < 1
                             || (bkDetList.size() > 0 && !((bkDetList.get(0)) instanceof BookingDetails))) {
                        BookingDetails bkDetails = new BookingDetails();
                        bkDetails.setCourse(new Course());
                        bkDetList.add(0, bkDetails);
                        booking.setBookingDetails(bkDetList);
                   } else if (((BookingDetails) bkDetList.get(0)).getCourse() == null
                             || ((BookingDetails) bkDetList.get(0)).getCourse()
                                       .getCourseId() == null) {
                        ((BookingDetails) bkDetList.get(0)).setCourse(new Course());
         @Override
         protected void validatePage(Object command, Errors errors, int page,
                   boolean finish) {
              BookActivityEvent activityEvent = (BookActivityEvent) command;
              if (finish) {
              super.validatePage(command, errors, page);
         * Validate client
         * @param booking
         * @param err
         private boolean checkForExistingActivities(ActivityMatrix userSuppliedActivity, Errors err)
              boolean exist = false;          
              List<ActivityMatrix> trainerActivityMatrixList =      activityMatrixFacade.getActivityMatrixBetweenDateRange(userSuppliedActivity.getTrainer().getTrainerId(),
                        userSuppliedActivity.getDateFrom(), userSuppliedActivity.getDateTo());
              if(ActivityTimeConstants.MOREDAYS.equals(userSuppliedActivity.getActivity().getTime()))
                   //checkForDates(trainerActivityMatrixList,);
              else if(ActivityTimeConstants.FULLDAY.equals(userSuppliedActivity.getActivity().getTime()))
                   // checkForDates(trainerActivityMatrixList,);
              else if(ActivityTimeConstants.AM.equals(userSuppliedActivity.getActivity().getTime()) ||
                        ActivityTimeConstants.PM.equals(userSuppliedActivity.getActivity().getTime()))
                   // checkForDates(trainerActivityMatrixList,);
         return exist;          
              * Check for existing bookings for a trainer and sets them on event object
              * @param request request.
              * @param event event.
              * @param err err.
              * @return true- bookings exist else false.
    private boolean checkForBookedCourses(HttpServletRequest request, BookActivityEvent event, Errors err)
         List<Booking> conflictBookingsList =      bookingFacade.loadBookingsByTrainerIdDateRange(event.getUserSuppliedActivity().getTrainer().getTrainerId(),
                   event.getUserSuppliedActivity().getDateFrom(),
                   event.getUserSuppliedActivity().getDateTo());
    request.getSession().setAttribute("conflictBookingsList",conflictBookingsList);     
                   if(conflictBookingsList!=null && conflictBookingsList.size()!=0)
                   event.setConflictBookings(conflictBookingsList);
                   return true;
                   else
                        return false;
         * Validate client
         * @param booking
         * @param err
         private void validateActivityMatrix(final BookActivityEvent activity, Errors err) {
    //          ValidationUtils.rejectIfEmptyOrWhitespace(err, "trainer.trainerId",
    //                    "required.trainer.trainerId", "Valid trainer needs to be selected.");
    ////          ValidationUtils.rejectIfEmptyOrWhitespace(err, "activity.activityId",
    ////                    "required.activity.activityId", "Valid activity needs to be selected.");
    //          if (err.getErrorCount() < 1)
    //                    if (activity.getDateFrom() == null) {
    //                         err.rejectValue("dateFrom", "required.dateFrom",
    //                                   "Valid Activity Start Date is required");
    //                    try
    //                         if (activity.getDateFrom() != null && activity.getDateTo() != null
    //                                   && (activity.getDateTo().before(activity.getDateFrom())))
    //                              err.rejectValue("dateTo", "required.dateTo",
    //                                        "Activity End Date Should be after start date.");
    //                    } catch (Exception ex) {
    //                         err.rejectValue("dateFrom",
    //                                   "dateFrom",
    //                                   "Improper dates, please provide valid dates.");
         * Validate Trainer
         * @param booking
         * @param e
         private void validateTrainer(final Booking booking, Errors e) {
              ValidationUtils.rejectIfEmptyOrWhitespace(e,
                        "bookingDetails[0].startDate",
                        "required.bookingDetails[0].startDate",
                        "Valid Booking Details startDate required.");
              ValidationUtils.rejectIfEmptyOrWhitespace(e,
                        "bookingDetails[0].trainer.trainerId",
                        "required.bookingDetails[0].trainer.trainerId",
                        "Valid Booking Details Trainer required.");
              if (e.getErrorCount() < 1)
                   for (BookingDetails bd : booking.getBookingDetails()) {
                        if (bd.getStartDate() == null) {
                             e.rejectValue("startDate", "required.bbb0",
                                       "Valid Booking details Start Date is required");
                        try {
                             if (bd.getStartDate() != null && bd.getEndDate() != null
                                       && (bd.getEndDate().before(bd.getStartDate())))
                                  e.rejectValue("endDate", "required.bbb0",
                                            "End Date Should be after starting date.");
                        } catch (Exception ex) {
                             e.rejectValue("bookingDetails[0].startDate",
                                       "before.bookingDetails[0].startDate",
                                       "Improper dates, please provide valid dates.");
                        if (bd.getTrainer() != null) {
                             e.rejectValue("trianerId", "required.trianerId",
                                       "Valid Trainer details required.");
         public BookingService getBookingFacade() {
              return bookingFacade;
         public void setBookingFacade(BookingService bookingFacade) {
              this.bookingFacade = bookingFacade;
         public CourseService getCourseFacade() {
              return courseFacade;
         public void setCourseFacade(CourseService courseFacade) {
              this.courseFacade = courseFacade;
         public VenueService getVenueFacade() {
              return venueFacade;
         public void setVenueFacade(VenueService venueFacade) {
              this.venueFacade = venueFacade;
         public ClientService getClientFacade() {
              return clientFacade;
         public void setClientFacade(ClientService clientFacade) {
              this.clientFacade = clientFacade;
         public TrainersService getTrainersFacade() {
              return trainersFacade;
         public void setTrainersFacade(TrainersService trainersFacade) {
              this.trainersFacade = trainersFacade;
         * getter method for activityFacade.
         * @return Returns the activityFacade.
         public ActivityService getActivityFacade() {
              return activityFacade;
         * setter method for activityFacade.
         * @param activityFacade The activityFacade to set.
         public void setActivityFacade(ActivityService activityFacade) {
              this.activityFacade = activityFacade;
         * getter method for activityMatrixFacade.
         * @return Returns the activityMatrixFacade.
         public ActivityMatrixService getActivityMatrixFacade() {
              return activityMatrixFacade;
         * setter method for activityMatrixFacade.
         * @param activityMatrixFacade The activityMatrixFacade to set.
         public void setActivityMatrixFacade(ActivityMatrixService activityMatrixFacade) {
              this.activityMatrixFacade = activityMatrixFacade;
         * getter method for bookingDetailsFacade.
         * @return Returns the bookingDetailsFacade.
         public BookingDetailsService getBookingDetailsFacade() {
              return bookingDetailsFacade;
         * setter method for bookingDetailsFacade.
         * @param bookingDetailsFacade The bookingDetailsFacade to set.
         public void setBookingDetailsFacade(BookingDetailsService bookingDetailsFacade) {
              this.bookingDetailsFacade = bookingDetailsFacade;
         class SqlDateEditor extends PropertyEditorSupport {
              private boolean isRequired = false;
              SqlDateEditor(boolean isRequired) {
                   this.isRequired = isRequired;
              public void setAsText(String text) throws IllegalArgumentException {
                   java.util.Date d = null;
                   if (!this.isRequired && !StringUtils.hasText(text)) {
                        setValue(null);
                   else
                        try {
                             d = dateFormat.parse(text);
                             setValue(new java.sql.Date(d.getTime()));
                        } catch (ParseException ex) {
                             throw new IllegalArgumentException("Could not parse date: " + ex.getMessage());
              public String getAsText() {
                   Date value = (java.sql.Date)getValue();
                   if (value != null) {
                        java.util.Date d = new java.util.Date(value.getTime());
                        return dateFormat.fo

    This topic is hopeless. Too much unnecessary code. Unformatted code. No question. No requirements. No step-by-step explanation how to reproduce problem. No expectations. No unexpectations/errors.
    Please read this how to get better help.

  • How to give styles to my HTMLDocument inside a JTextPane?

    I have a JTextPane with a HTMLDocument attached to it. How can I style the text which is typed in? For example I want to set a larger font. How can I do this in my example?
    Another problem is that when I hit the alignment buttons the text is actually aligned according to the hit button but the JEditorPane doesn't show the text correctly. It also doesn't enter a line feed when typing ENTER key.
    Can someone help me on this please?
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.IOException;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextPane;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.html.HTMLDocument;
    import javax.swing.text.html.HTMLEditorKit;
    public class AdditionalText extends JFrame implements ActionListener {
         private JButton leftAlign;
         private JButton centerAlign;
         private JButton rightAlign;
         private JTextPane editor;
         private JButton save;
         private JButton dump;
         public AdditionalText() {
              setTitle("Test Frame");
              JPanel topToolbar = new JPanel();
              leftAlign = new JButton("Left");
              centerAlign = new JButton("Center");
              rightAlign = new JButton("Right");
              ActionListener alignLeft = new HTMLEditorKit.AlignmentAction("alignLeft", 0);
              ActionListener alignCenter = new HTMLEditorKit.AlignmentAction("alignCenter", 1);
              ActionListener alignRight = new HTMLEditorKit.AlignmentAction("alignRight", 2);
              leftAlign.addActionListener(alignLeft);
              centerAlign.addActionListener(alignCenter);
              rightAlign.addActionListener(alignRight);
              topToolbar.add(leftAlign);
              topToolbar.add(centerAlign);
              topToolbar.add(rightAlign);
              editor = createEditor();
              JPanel bottomToolbar = new JPanel();
              save = new JButton("Save");
              save.addActionListener(this);
              dump = new JButton("Dump");
              dump.addActionListener(this);
              bottomToolbar.add(save);
              bottomToolbar.add(dump);
              getContentPane().add(BorderLayout.NORTH, topToolbar);
              getContentPane().add(BorderLayout.CENTER, editor);
              getContentPane().add(BorderLayout.SOUTH, bottomToolbar);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              setSize(new Dimension(640, 480));
              setLocation((screenSize.width - 640) / 2, (screenSize.height - 480) / 2);
         private JTextPane createEditor() {
              JTextPane textPane = new JTextPane() {
                   public void paintComponent(Graphics g) {
                        Graphics2D g2 = (Graphics2D) g;
                        g2.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                        g2.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
                        g2.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
                        g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
                        g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                        g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
                        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
                        super.paintComponent(g2);
              textPane.setEditorKit(new HTMLEditorKit());
              return textPane;
         public void actionPerformed(ActionEvent e) {
              HTMLDocument htmlDocument = (HTMLDocument) editor.getDocument();
              if(e.getSource() == save) {
                   HTMLEditorKit kit = (HTMLEditorKit)editor.getEditorKitForContentType("text/html");
                   try {
                        kit.write(System.out, htmlDocument, 0, htmlDocument.getLength());
                   } catch (IOException ex) {
                        ex.printStackTrace();
                   } catch (BadLocationException ex) {
                        ex.printStackTrace();
              } else if(e.getSource() == dump) {
                   htmlDocument.dump(System.err);
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (ClassNotFoundException e) {
                   e.printStackTrace();
              } catch (InstantiationException e) {
                   e.printStackTrace();
              } catch (IllegalAccessException e) {
                   e.printStackTrace();
              } catch (UnsupportedLookAndFeelException e) {
                   e.printStackTrace();
              AdditionalText at = new AdditionalText();
              at.show();
    }

    I created a class that can be used to highlight Java source code. Most of the code is for handling multi line comments. If you just want it to highlight certain keywords then you can get rid of all that logic. In case your interested, the code can be downloaded from here:
    http://www.discoverteenergy.com/files/SyntaxDocument.java

  • Inserting big text in a JEditorPane / HTMLDOcument

    Hi.
    I have noticed a strange behaivour of a JEditorPane with an HTMLDocument in it.
    If i put a big text in it AT ONCE (setText() or insertString() or insetHTML, doesnt matter),
    the preformance of the whole app gets soooo slow, f.e if i type in just a single character afterwards, i takes about 3 seconds till it appears in the document.
    BUT if i put the big text into smaller pieces, f.e i paste in all the small text-parts, then i cant see
    any performance-problems afterwards.
    Has anybody an idea why it is like that ?!?
    Or do i something wrong when i put in the text at once ?
    (Im using the actual JDK1.4.0 and JRE1.4.0 b92)
    Thanks for help,
    greetings,
    Huni.

    Hello Andrea!
    You have to use a variable like TV or a text channel for every column you want to set. There is no direct way to fill a cell. In your script you only have to set the variable or channel. As you expected you have to use a vbCRLF to get multiline text. DIAdem will display multiline text but did not recognize it. That means that the program do not make a vertical alignment. The first line will be vertical centerted and all other lines will be below. Result: A white gap above the text! You have to 'play' with the cell and text height to get a half-decent text display. BTW: I made my tests with DIAdem 9.
    Matthias
    Matthias Alleweldt
    Project Engineer / Projektingenieur
    Twigeater?  

  • How to put Nested List in HTMLDocument  in JTextPane(JEditorPane)

    How to put Nested List in HTMLDocument in JTextPane(JEditorPane). I was trying to put nested Bullets and Numbering but found that not enough support is provided for it. The HTMLEditorKit behaves abnormally.
    There are two ways to do that:
    1) just extract the whole text by getText, but the problem is you don't have the postion where the cursor was when the event was triggered so u can't add ur text to it , even if u extracted the text at cursor there can be multiple copies, so no way...also if u change it and reinsert the whole text the atributeset for whole text is lost.
    2) So the only way is work with jugglery of Elements, which is full of bugs. I find it very difficult to move backward in it and insert a tag around a tag. Such a simple thing and almost no way. If anybody has any ideas please mail me.
    Thanx in Advance

    Settings > Mail, Contacts, Calendars > Contacts > Sort Order/Display Order 'First, Last'

  • JTextPane: Problem adding hyperlinks & images

    Hi,
    I have a problem and I just can't figure out how to solve it.
    I need to implement a simple Editor for HTML files. Lucky for me, most of the functionality i need is already provided by swing, but i still need to add images and hyperlinks to my document. Especially, i need to be able to select some text, click on a button and turn it into a hyperlink. If an image is within the selected range, then the image should be included in the hyperlink as well (just as you would expect it to be).
    Adding images works so far, using this code (i'll take care of actually loading the image when the rest works).
    JEditorPane editor = getEditor( e );
    HTMLDocument doc = (HTMLDocument) getStyledDocument( editor );
    MutableAttributeSet attr = new SimpleAttributeSet();
    attr.addAttribute( StyleConstants.NameAttribute, HTML.Tag.IMG );
    attr.addAttribute( HTML.Attribute.SRC, "p.gif" );
    try {
         doc.insertString( editor.getCaretPosition(), " ", attr );
    } catch (BadLocationException e1) {
         e1.printStackTrace();
    }But when i try to do the same with HTML.Tag.A and HTML.Attribute.HREF, the selected text disappears from the code (it is still visible in the JTextPane, though) and is replaced by . I just don't seem to get the whole AttributeSet mechanism or which attributes need to be set to which values.
    I have seriously been stuck on this stuff for over one day now, and went through half a million tutorials, but can't figure it out - and i can't imagine that it is that complicated to do something like that.
    By the way, I don't care whether or not you can click on the link in the JTextPane. The whole application is just for editing purposes and the document's content will be uploaded to a webserver at a later point.
    I hope there's somebody who can help me out here.
    Thanks in advance,
    ak87

    Doesn't anyone have a hint for me here?

  • JEditorPane html display problem

    Hello,
    I'm running a JEditorPane inside an Applet for a project im working on. The source included below is an over-simplified version that produces the same results. The problem i'm having is that the html displays in an odd fasion in the JEditorPane.
    Since I cant include a screenshot let me attempt to describe it. Regardless of the FONT face in the html the paragraph displays as you would expect in the JEditorPane until the last line. The last has extra horizontal space separating it from the rest of the paragraph. This seems completely arbitrary. There is nothing in the html code near the line break.
    I've linked this problem to the font face attribute tags. Regardless of the font I choose it displays improperly. Any idea on how to remove this spacing problem in my JEditorPane?
    I'm using NetBeans 3.5.1 and SDK 1.4.2. I've tested this problem in the AppletViewer as well as online in a web browser.
    * CourierTest.java
    * Created on July 24, 2004, 8:28 PM
    import java.awt.Font;
    import java.io.*;
    * @author LD Miller
    public class CourierTest extends javax.swing.JApplet {
    String html;
    /** Initializes the applet CourierTest */
    public void init() {
    initComponents();
    html = "<P class=MsoNormal style=\"MARGIN: 0in 0in 0pt\"><FONT size=3><FONT face=\"Times New Roman\">What is event-driven programming?It is a <I>computer programming</I> paradigm that is different from traditional, sequential programming. In traditional, sequential programming, one could follow the program and plot out exactly the sequence of execution of the program. However, in event-driven programming, it is not possible to plot out exactly the sequence of execution of the program since flow of the execution is determined by the events. Event-driven programming allows a program to interact with users and re-act to user-generated events in a more efficient and effective manner. </FONT></FONT></P>";
    jTextPane1.setContentType("text/html");
    jTextPane1.setText(html);
    /** This method is called from within the init() method to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextPane1 = new javax.swing.JTextPane();
    jScrollPane1.setViewportView(jTextPane1);
    getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration

    1) I have complex html page (having lot of html controls).
    .when i resize the container, controls gets overlapped.
    shall we avoid this? to my experience JEditorPane deviates from the display of typical browsers when HTML is displayed that contains complex table layouts (tables nested in other tables or non-explicit or non-existent size expressions in tables for instance). I recommend to try and simplify layout complexity as a workaround. Start with a most simple page and increase complexitiy until display gets unsatisfactory.
    2) I used JEditorPane. My html contents are stored in
    text. i called setText()...whether i need to use
    HTMLDocument, HTMLEditorKit etc...to render
    html in better way...I did not understand your second point, what is the question?
    Ulrich

  • Problem with SAX parser - entity must finish with a semi-colon

    Hi,
    I'm pretty new to the complexities of using SAXParserFactory and its cousins of XMLReaderAdapter, HTMLBuilder, HTMLDocument, entity resolvers and the like, so wondered if perhaps someone could give me a hand with this problem.
    In a nutshell, my code is really nothing more than a glorified HTML parser - a web page editor, if you like. I read in an HTML file (only one that my software has created in the first place), parse it, then produce a Swing representation of the various tags I've parsed from the page and display this on a canvas. So, for instance, I would convert a simple <TABLE> of three rows and one column, via an HTMLTableElement, into a Swing JPanel containing three JLabels, suitably laid out.
    I then allow the user to amend the values of the various HTML attributes, and I then write the HTML representation back to the web page.
    It works reasonably well, albeit a bit heavy on resources. Here's a summary of the code for parsing an HTML file:
          htmlBuilder = new HTMLBuilder();
    parserFactory = SAXParserFactory.newInstance();
    parserFactory.setValidating(false);
    parserFactory.setNamespaceAware(true);
    FileInputStream fileInputStream = new FileInputStream(htmlFile);
    InputSource inputSource = new InputSource(fileInputStream);
    DoctypeChangerStream changer = new DoctypeChangerStream(inputSource.getByteStream());
    changer.setGenerator(
       new DoctypeGenerator()
          public Doctype generate(Doctype old)
             return new DoctypeImpl
             old.getRootElement(),
                              old.getPublicId(),
                              old.getSystemId(),
             old.getInternalSubset()
          resolver = new TSLLocalEntityResolver("-//W3C//DTD XHTML 1.0 Transitional//EN", "xhtml1-transitional.dtd");
          readerAdapter = new XMLReaderAdapter(parserFactory.newSAXParser().getXMLReader());
          readerAdapter.setDocumentHandler(htmlBuilder);
          readerAdapter.setEntityResolver(resolver);
          readerAdapter.parse(inputSource);
          htmlDocument = htmlBuilder.getHTMLDocument();
          htmlBody = (HTMLBodyElement)htmlDocument.getBody();
          traversal = (DocumentTraversal)htmlDocument;
          walker = traversal.createTreeWalker(htmlBody,NodeFilter.SHOW_ELEMENT, null, true);
          rootNode = new DefaultMutableTreeNode(new WidgetTreeRootNode(htmlFile));
          createNodes(walker); However, I'm having a problem parsing a piece of HTML for a streaming video widget. The key part of this HTML is as follows:
                <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
                  id="client"
            width="100%"
            height="100%"
                  codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
                  <param name="movie" value="client.swf?user=lkcl&stream=stream2&streamtype=live&server=rtmp://192.168.250.206/oflaDemo" />
             etc....You will see that the <param> tag in the HTML has a value attribute which is a URL plus three URL parameters - looks absolutely standard, and in fact works absolutely correctly in a browser. However, when my readerAdapter.parse() method gets to this point, it throws an exception saying that there should be a semi-colon after the entity 'stream'. I can see whats happening - basically the SAXParser thinks that the ampersand marks the start of a new entity. When it finds '&stream' it expects it to finish with a semi-colon (e.g. much like and other such HTML characters). The only way I can get the parser past this point is to encode all the relevant ampersands to %26 -- but then the web page stops working ! Aaargh....
    Can someone explain what my options are for getting around this problem ? Some property I can set on the parser ? A different DTD ? Not to use SAX at all ? Override the parser's exception handler ? A completely different approach ?!
    Could you provide a simple example to explain what you mean ?
    Thanks in anticipation !

    You probably don't have the ampersands in your "value" attribute escaped properly. It should look like this:
    value="client.swf?user=lkcl&stream=...{code}
    Most HTML processors (i.e. browsers) will overlook that omission, because almost nobody does it right when they are generating HTML by hand, but XML processors won't.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • HELP!!! character display problem in JEditorPane

    hi,
    I got a headache with my program which needs to display multiple language html page in a JEditorPane. For example, if user requests a Chinese page then page is read in from an inputstreamreader using Chinese charset encoding. But what JEditorPane displays is squares and this is a very common font problem. I did everything I can
    copy font.properties.zh to font.properties
    set JEditorPane font as Font("SIMSUN",Font.PLAIN,12)
    with the bug unsolved so far.
    I am using Windows 2000/ME in UK locale.
    Anybody could help please???

    yes, the input data, for example in the case of Chinese Simpilify Character, is read in using a decoder with charset GB2312. I think I can print them out on prompt console but in a unrecognizable format.
    Anyway, I would like to reconfirm the steps I took: (Presumably I know I am going to load a Chinese page)
    1. rename font.properties.zh to font.properties
    2. set the font of JEditorPane as ("SIMSUN",Font.PLAIN,12)
    3. when try to load a Chinese page, there should be a ChangedCharSetException. extract the charset from the exception and use it to construct a new InputStreamReader.
    4. I also set the content-type of JEditorPane as something like "text/html; charset=gb2312"
    5. read in the data and parse it into a HTMLDocument instance.
    6. finally use setDocument method to display the document on the JEditorPane.
    In this way, the page gets displayed in unknown characters.
    Anybody could show me something different but feasiable? Please!!!

  • Is that a problem of SwingUtilities.paintComponent() method ?

    Hello Everyone,
    I have succeeded to write the HTML contents of jeditorpane to buffered image. But the output image shows everything except the Radio Buttons,Text Boxes and Buttons on that HTML page. Please suggest me where might be the problem.
    Compare two images,
    1> one which is displayed on a jframe, which displays Radio button, Text Box, Submit Button.
    2> another one which is created on C: drive, named as out.jpg. This image doesn't have Radio button, Text Box, Submit Button.
    Note: I don't want to display an image anywhere. Not on even JFrame. [ I have implemented the code for displaying just to show you the difference in images]
    Thanks and Regards.
    import java.awt.image.BufferedImage;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.awt.*;
    import java.net.MalformedURLException;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    import javax.swing.JEditorPane;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import java.net.URL;
    import javax.imageio.ImageIO;
    public class HTMLPageToImage
            static class Kit extends HTMLEditorKit
                public Kit() {
                public Document createDefaultDocument()
                    HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
                    doc.setTokenThreshold(Integer.MAX_VALUE);
                    doc.setAsynchronousLoadPriority(-1);
                    return doc;
               public ViewFactory getViewFactory() {
                    return new SynchronousImageViewFactory(super.getViewFactory());
                static class SynchronousImageViewFactory implements ViewFactory {
                    ViewFactory impl;
                    SynchronousImageViewFactory(ViewFactory impl) {
                        this.impl = impl;
                    public View create(Element elem) {
                        View v = impl.create(elem);
                        if((v != null) && (v instanceof ImageView)) {
                            ((ImageView)v).setLoadsSynchronously(true);
                        return v;
        public static BufferedImage getCapturedImage(String filePath, int width, int height)
            JEditorPane jep = new JEditorPane();
            Kit kit = new Kit();
            //String str = "file:" + filePath;
            String str = "http://" + filePath;
            URL url;
            try {
                url = new URL(str);
                try {
                    jep.setEditorKit(kit);
                    jep.setEditable(false);
                    jep.setContentType("text/html");
                    jep.setPage(url);
                    System.out.println("jep size : " + jep.getPreferredSize());
                    width = jep.getPreferredSize().width;
                    height = jep.getPreferredSize().height;
                        //--- Just to show that Radio Buttons, Text Box, Submit Buttons are displayed properly ----
                        JPanel p = new JPanel();
                        p.setVisible(true);
                        p.setSize(width,height);
                        p.add(jep);
                        JFrame f = new JFrame();
                        f.setSize(1024,768);
                        f.setVisible(true);
                        f.add(p);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                } catch (IOException ex) {
                    ex.printStackTrace();
            } catch (MalformedURLException ex) {
                ex.printStackTrace();
            BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics2D bufferedImageGraphics2D = bufferedImage.createGraphics();
            Container c = new Container();
            SwingUtilities.paintComponent(bufferedImageGraphics2D, jep, c, 0, 0, width, height);
            bufferedImageGraphics2D.dispose();
            return bufferedImage;
        public static void main(String[] args) throws FileNotFoundException,IOException
            //BufferedImage image = HTMLPageToImage.getCapturedImage("E:\\Texture\\my.html", 1024, 768);
            BufferedImage image = HTMLPageToImage.getCapturedImage("www.google.com", 1024, 768);
            com.sun.image.codec.jpeg.JPEGImageEncoder enc = JPEGCodec.createJPEGEncoder(new FileOutputStream("c:\\out.jpg"));
            enc.encode(image);
            System.out.println("See the image out.jpg created on C: drive ! ");
    }Edited by: nikhil_shravane on Jun 27, 2008 6:42 AM
    Edited by: nikhil_shravane on Jun 27, 2008 7:34 AM
    Edited by: nikhil_shravane on Jun 27, 2008 8:12 AM

    Hi Again, TextBox, TextArea and buttons are visible only when I place the jeditorpane with an HTML on a JPanel and JFrame before writing the captured image on a buffered Image. But when I directly captures the image from jeditorpane without placing it on JPanel and JFrame, the captured image doesn't show the TextBox, TextArea and Buttons. I want to capture the HTML image and write it directly to buffered Image. For that I don't want to open JPanel and JFrame. I can write the captured HTML from jeditorpane directly to the buffered image, but that image doesnt have tha TextBox, TextArea, Buttons and Tables. Following is the method which writes the captured HTML from jeditorpane directly to the buffered image.
    import java.awt.*;
    import java.awt.image.*;
    import java.io.IOException;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.html.*;
    * @author Nikhil Shravane
    public class WebImage {
        JEditorPane jep;
        Container c;
        BufferedImage bufferedImage ;
        Graphics2D bufferedImageGraphics2D;
        Object object;
        Kit kit;
         WebImage()     {
             object = new Object();
        static class Kit extends HTMLEditorKit {
                // Override createDefaultDocument to force synchronous loading
                public Document createDefaultDocument() {
                        HTMLDocument doc = (HTMLDocument) super.createDefaultDocument();
                        doc.setTokenThreshold(Integer.MAX_VALUE);
                        doc.setAsynchronousLoadPriority(-1);
                        return doc;
        public synchronized BufferedImage getCapturedImage(String src, int width, int height)    {
            jep = new JEditorPane();
            kit = new Kit();
            jep.setEditorKit(kit);
            jep.setEditable(false);
            jep.setMargin(new Insets(0,0,0,0));
            synchronized(object)        {
                try {
                    jep.setPage(src);
                } catch (IOException ex) {
                    ex.printStackTrace();
                height = width;//  * jep.getPreferredSize().height / jep.getPreferredSize().width;
                bufferedImage = new BufferedImage((int)width, (int)height, BufferedImage.TYPE_INT_RGB);
                bufferedImageGraphics2D = bufferedImage.createGraphics();
                c = new Container();
                SwingUtilities.paintComponent(bufferedImageGraphics2D, jep, c, 0, 0, (int)width, (int)height);
                bufferedImageGraphics2D.dispose();
            JLabel label = new JLabel(new ImageIcon(bufferedImage));
            JOptionPane.showMessageDialog(null, label, "clipped image",
                                              JOptionPane.PLAIN_MESSAGE);
            return bufferedImage;
        public static void main(String[] args) {
            WebImage webImage = new WebImage();
                BufferedImage image = webImage.getCapturedImage("http://www.google.com/", 640, 480);
                //BufferedImage image = webImage.getCapturedImage("file:\\E:\\Texture\\my.html", 640, 480);
                // you can write this buffered image anywhere...
    }Above code will capture the HTML image and write it to buffered image and returns the buffered image.
    Please Suggest me the way, so that I can see the Buttons, TextBox, TextArea, Tables etc.
    Thanks and Regards,
    Nikhil

  • No compilation error but have problems when running.

    Hello all,
    After implementing the examples given from the TextComponentJavaDemo in Java Tutorials I tried to get the fonts to change text in the JEditorPane but to no avail.
    The problem I am having now is some java.lang.Null.PointerException .
    The errors are shown as follows:
    Exception in thread "main" java.lang.NullPointerException
    at guiClient.createActionTable<guiClient.java :191>
    at guiClient.<init> <guiClient.java:52>
    at guiClient.main <guiClient.java:308>
    Here is the whole code for the syntax but it cannot be compiled:
    /* * My GUI Client */
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    //for HTML Headers
    import javax.swing.text.StyledEditorKit.*;
    import javax.swing.text.html.HTMLEditorKit.*;
    import javax.swing.text.html.*;
    import javax.swing.event.HyperlinkListener;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.event.HyperlinkEvent.EventType;
    import javax.swing.text.html.HTMLFrameHyperlinkEvent;
    import javax.swing.text.*;
    //for layout managers
    import java.awt.event.*;
    //for action and window events
    import java.io.*;
    import java.net.*;
    import java.awt.GraphicsEnvironment;
    import java.util.HashMap;
    public class guiClient extends JFrame implements ActionListener {
    protected static final String textFieldString = "JTextField";
    protected static final String loadgraphicString = "LoadGraphic";
    protected static final String connectString = "Connect";
    static JEditorPane editorPane;
    static JPanel layoutPanel = new JPanel(new BorderLayout());
    static JPanel controlPanel = new JPanel(new BorderLayout());
    static PrintStream out;
    static DrawPanel dPanel;
    static DrawControls dControls;
    static AnimationButtons aControls;
    static String userString;
    static JTextField userName = new JTextField();
    public static JMenuBar menuBar;
    private static JButton connectbutton = new JButton("Connect");
    static boolean CONNECTFLAG = false;
    AbstractDocument doc;
    HashMap actions;
    //create the gui interface
    public guiClient() {
         super("My Client");
    //Create a regular text field.
         JTextField textField = new JTextField(10);
         textField.setActionCommand(textFieldString);
         textField.addActionListener(this);
    //Create an editor pane.
        createActionTable(editorPane); //From TextComponentDemo
        editorPane = new JEditorPane();
         editorPane.setContentType("text");
         editorPane.setEditable(true);
    //set up HTML editor kit
         HTMLDocument m_doc = new HTMLDocument();
         editorPane.setDocument(m_doc);
         HTMLEditorKit hkit = new HTMLEditorKit();
         editorPane.setEditorKit( hkit );
         editorPane.addHyperlinkListener(new HyperListener());
    //Create whiteboard
            dPanel = new DrawPanel();
            dControls = new DrawControls(dPanel);
            aControls = new AnimationButtons (dPanel);
            JPanel whiteboard = new JPanel();
            whiteboard.setLayout(new BorderLayout());
            whiteboard.setPreferredSize(new Dimension(300,300));
            whiteboard.add("Center",dPanel);
            whiteboard.add("South",dControls);
           // whiteboard.add("North",aControls);
         JScrollPane editorScrollPane = new JScrollPane(editorPane);
         editorScrollPane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
         editorScrollPane.setPreferredSize(new Dimension(250, 145));
         editorScrollPane.setMinimumSize(new Dimension(50, 50));
    //     StyledDocument styledDoc = editorPane.getStyledDocument();
    //put everything in a panel
         JPanel contentPane = new JPanel();
         contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    //add whiteboard
         contentPane.add(whiteboard);
    //add editor box
         contentPane.add(editorScrollPane);
    //add spacer
         contentPane.add(Box.createRigidArea(new Dimension(0,5)));
    //add textfield
         contentPane.add(textField);
    //set up layout pane
         layoutPanel.add(BorderLayout.WEST,new Label("Name: ")); //add a label
         layoutPanel.add(BorderLayout.CENTER, userName ); //add textfield for user names
         layoutPanel.add(BorderLayout.SOUTH, connectbutton);//add dropdown box for fonts
         contentPane.add(layoutPanel);
         contentPane.add(controlPanel);
         contentPane.add(aControls);
    //Create the menu bar.
            menuBar = new JMenuBar();
            setJMenuBar(menuBar);
    //Build the first menu.
         JMenu menu = new JMenu("File");
         JMenu styleMenu = createStyleMenu();
         menu.setMnemonic(KeyEvent.VK_F);
         menuBar.add(menu);
         menuBar.add(styleMenu);
    //a group of JMenuItems
         JMenuItem menuItem = new JMenuItem("Load Graphic", KeyEvent.VK_L);
         menu.add(menuItem);
            menuItem.setActionCommand(loadgraphicString);
         menuItem.addActionListener(this);
            connectbutton.setActionCommand(connectString);
            connectbutton.addActionListener(this);
         setContentPane(contentPane);
    protected JMenu createStyleMenu() {
            JMenu menu = new JMenu("Style");
            Action action = new StyledEditorKit.BoldAction();
            action.putValue(Action.NAME, "Bold");
            menu.add(action);
            action = new StyledEditorKit.ItalicAction();
            action.putValue(Action.NAME, "Italic");
            menu.add(action);
            action = new StyledEditorKit.UnderlineAction();
            action.putValue(Action.NAME, "Underline");
            menu.add(action);
            menu.addSeparator();
            menu.add(new StyledEditorKit.FontSizeAction("12", 12));
            menu.add(new StyledEditorKit.FontSizeAction("14", 14));
            menu.add(new StyledEditorKit.FontSizeAction("18", 18));
            menu.addSeparator();
            menu.add(new StyledEditorKit.FontFamilyAction("Serif",
                                                          "Serif"));
            menu.add(new StyledEditorKit.FontFamilyAction("SansSerif",
                                                          "SansSerif"));
            menu.addSeparator();
            menu.add(new StyledEditorKit.ForegroundAction("Red",
                                                          Color.red));
            menu.add(new StyledEditorKit.ForegroundAction("Green",
                                                          Color.green));
            menu.add(new StyledEditorKit.ForegroundAction("Blue",
                                                          Color.blue));
            menu.add(new StyledEditorKit.ForegroundAction("Black",
                                                          Color.black));
            return menu;
         protected SimpleAttributeSet[] initAttributes(int length) {
            //Hard-code some attributes.
            SimpleAttributeSet[] attrs = new SimpleAttributeSet[length];
            attrs[0] = new SimpleAttributeSet();
            StyleConstants.setFontFamily(attrs[0], "SansSerif");
            StyleConstants.setFontSize(attrs[0], 16);
            attrs[1] = new SimpleAttributeSet(attrs[0]);
            StyleConstants.setBold(attrs[1], true);
            attrs[2] = new SimpleAttributeSet(attrs[0]);
            StyleConstants.setItalic(attrs[2], true);
            attrs[3] = new SimpleAttributeSet(attrs[0]);
            StyleConstants.setFontSize(attrs[3], 20);
            attrs[4] = new SimpleAttributeSet(attrs[0]);
            StyleConstants.setFontSize(attrs[4], 12);
            attrs[5] = new SimpleAttributeSet(attrs[0]);
            StyleConstants.setForeground(attrs[5], Color.red);
            return attrs;
        private void createActionTable(JTextComponent textComponent) {
            actions = new HashMap();
            Action[] actionsArray = textComponent.getActions();
            for (int i = 0; i < actionsArray.length; i++) {
                Action a = actionsArray;
    actions.put(a.getValue(Action.NAME), a);
    private Action getActionByName(String name) {
    return (Action)(actions.get(name));
    static private void insertTheHTML(JEditorPane editor, String html, int location) throws IOException {
         HTMLEditorKit kit = (HTMLEditorKit) editor.getEditorKit();
         Document doc = editor.getDocument();
         StringReader reader = new StringReader(html);
         try {
              kit.read(reader, doc, location);
         } catch (BadLocationException e) {}
    //listen for actions being performed and process them
    public void actionPerformed(ActionEvent e) {
    //if the action is from the textfield (e.g. user hits enter)
         if (e.getActionCommand().equals(textFieldString)) {
              JTextField fromUser = (JTextField)e.getSource();
         if (fromUser != null){
    //place user text in editor pane
    //send message to server
                   if (userName.getText() != null) {
                        userString = userName.getText().trim();
                   out.println(userString + ": " + fromUser.getText());
              fromUser.setText("");
         } else if(e.getActionCommand().equals(connectString)) {
              CONNECTFLAG = true;
    } else if (e.getActionCommand().equals(loadgraphicString) ) {
              final JFileChooser fc = new JFileChooser();
              int returnVal = fc.showOpenDialog(this);
              if (returnVal == JFileChooser.APPROVE_OPTION) {
                   File file = fc.getSelectedFile();
                   dPanel.loadImage(file.getAbsolutePath());
                   sendImage(file);
    //append text to the editor pane and put it at the bottom
    public static void appendText(String text) {
         if (text.startsWith("ID ") ) {
              userString = text.substring(3);
         } else if (text.startsWith("DRAW ") ) {
              if (text.regionMatches(5,"LINE",0,4)) {
    dPanel.processLine(text);
         }else if (text.regionMatches(5,"POINTS",0,5)) {
         dPanel.processPoint(text);
         } else if (text.startsWith("IMAGE ") ) {
    int len = (new Integer( text.substring(6, text.indexOf(",")))).intValue();
    //get x and y coordinates
         byte[] data = new byte[ (int)len ];
         int read = 0;
    try {
         while (read < len) {
         data = text.getBytes( text.substring(0, len) );
    } catch (Exception e) {}
         Image theImage = null;
         theImage = dPanel.getToolkit().createImage(data);
         dPanel.getToolkit().prepareImage(theImage, -1, -1, dPanel);
         while ((dPanel.getToolkit().checkImage(theImage, -1, -1, dPanel) & dPanel.ALLBITS) == 0) {}
              dPanel.drawPicture(0, 0, theImage);
    } else {
    //set current position in editorPane to the end
              editorPane.setCaretPosition(editorPane.getDocument().getLength());
    //put text into the editorPane
              try {
                   insertTheHTML(editorPane, text, editorPane.getDocument().getLength());
              } catch (IOException e) {}
    } //end of appendText(String)
    public void sendImage(File file) {
    //find length of file
         long len = file.length();
    //read file into byte array
         byte[] byteArray = new byte[(int)len];
         try {
              FileInputStream fstream = new FileInputStream(file);
              if (fstream.read(byteArray) < len) {
    //error could not load file
              } else {
              out.println("IMAGE " + len + ",");
                   out.write(byteArray, 0, (int)len); //write file to stream
         } catch(Exception e){}
    //run the client
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    final guiClient frame = new guiClient();
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
         String ipAddr=null, portNr=null;
              if (args.length != 2) {
                   System.out.println("USAGE: java guiClient IP_Address port_number");
                   System.exit(0);
              } else {
         ipAddr = args[0];
              portNr = args[1];
              JFrame frame = new guiClient();
              frame.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) { System.exit(0); }
              frame.pack();
              frame.setVisible(true);
              while(CONNECTFLAG == false){}
    //sames as previous client,
    //set up connection and then listen for messages from the Server
              String socketIP = ipAddr;
              int port = Integer.parseInt(portNr);
    //the IP address of the machine where the server is running
              Socket theSocket = null;
    //communication line to the server
              out = null;
    //for message sending
              BufferedReader in = null;
    //for message receiving
              try {
              theSocket = new Socket(socketIP, port );
    //try to connect
              out = new PrintStream(theSocket.getOutputStream());
                   dPanel.out = out;
    //for client to send messages
              in = new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
                   BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
                   String fromServer;
                   while ((fromServer = in.readLine()) != null) {
                   appendText(fromServer);
                   if (fromServer.equals("BYE")) {
                        appendText("Connection Closed");
                        break;
              out.close();
    //close all streams
              in.close();
              theSocket.close();
    //close the socket
         } catch (UnknownHostException e) {
    //if the socket cannot be openned
              System.err.println("Cannot find " + socketIP);
              System.exit(1);
              } catch (IOException e) { //if the socket cannot be read or written
              System.err.println("Could not make I/O connection with " + socketIP);
              System.exit(1);
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    Can someone tell me what's the problem with the syntax?

    For your nullPointerException, you have to create your textPane before calling createActionTable          editorPane = new JEditorPane();
              createActionTable(editorPane); //From TextComponentDemoAlso, I would like to point out the following :
    - you're creating your guiClient twice in the main method : at the beginning and at the end through the createAndShowGUI.
    - for no apparent reason, all your member fields are declared static.
    - naming conventions : class names must start with a capital letter.

  • Replacing html tags in a htmldocument

    Hi Java Gurus
    I have a htmldocument which has the bacjground set to black and foreground to white.
    When i print the document i see the text in white color ( rather invisible).
    I thought the foreground color of the document needs to be changed.
    How can i do this ?
    Thanks in advance
    Naveen

    rest_in_peace wrote:
    You'll get a faster, more effective response to your questions by including as much relevant information as possible upfront. This should include:
    <li>Full APEX version
    <li>Full DB version and edition
    <li>Web server architecture (EPG, OHS or APEX listener)
    <li>Browser(s) and version(s) used
    <li>Theme
    <li>Template(s)
    <li>Region/item type(s)
    Read the FAQ and forum sticky threads for more information on using the forum effectively.
    With APEX we're fortunate to have a great resource in apex.oracle.com where we can reproduce and share problems. Reproducing things there is the best way to troubleshoot most issues.
    I have created a form on a table. Now one of the fields in the form is a display only field and its datatype is varchar2.There are a number of different ways of "creating a form on a table" and of making "display only fields". Describe exactly what you mean using actual APEX terminology of regions, items, and their attributes.
    The data in the database column of the field contains html tags which is getting displayed as it is without being parsed. It is not possible for me to edit the data in the table itself since there are thousands of data. So I need a way to display the data with the html tags parsed and not displayed as it is. Please any help would be grealy appreciated. How this is achieved is version-dependent: provide the full APEX version.

  • Inserting blockquote tags into a HTMLDocument

    G'Day,
    I'm having a bit of trouble inserting <blockquote> tags into a HTMLDocument.
    Basically I want the blockquote tags to implement an indent feature. ie, you click a button and all the text in the current paragraph gets surrunded by blockquote tags, which when rendered makes it indent.
    The code I'm using is:
    Element current = doc.getParagraphElement(pos);
    try
    doc.insertBeforeStart(current, "<blockquote>");
    doc.insertAfterEnd(current, "</blockquote>");
    catch (Exception e)
    lets say we have html like this:
    <p>
    hello
    </p>
    when this code runs, i get:
    <blockquote>
    </blockquote>
    <p>
    hello
    </p>
    I think that when I do the insertBeforeStart and insert the opening tag, after that completes the document is rendered and the end tag is put in there automatically???
    So, can anyone help me out here and suggest a better way?
    Cheers,
    Leighton.

    I've been trying to get <blockquote> insert working in an editor but it seems to be a quite difficult task even if it's only about inserting a couple of tags into the right slot! This is the closest I got:
    HTMLDocument doc = (HTMLDocument)editor.getDocument();
    int start = editor.getCaretPosition()
    int paraStart = doc.getParagraphElement(start).getStartOffset();
    int paraEnd = doc.getParagraphElement(start).getEndOffset();
    String insideBlockQuotes = doc.getText(paraStart, paraEnd - paraStart);
    doc.setOuterHTML(doc.getParagraphElement(start),"<blockquote><p>"+insideBlockQuotes+"</p></blockquote>");
    This is how it works: Get the current paragraphs start and end positions, read the text between the start and end into a string, replace the paragrapElement with <blockquote><p>..the text from string..</p></blockquote>.
    This works 'in about' but it's far from perfect.. it has the following problems:
    1. It looses all formatting from the quoted paragraph (bold etc. tags from the quoted part)
    2. It assumes that the paragraphElement was a <p> (could have been another element too!)
    3. It's ugly
    Anybody come up with a better way to use blockquote?

  • Some problems about insert String into JTextPane

    here is the colde:
    HTMLEditorKit kit = new HTMLEditorKit();
    HTMLDocument doc =(HTMLDocument)kit.createDefaultDocument();
    String str="hello world";
    SimpleAttributeSet attr =new MutableAttributeSet();
    StyleConstants.setFontFamily(attr, "Times New Roman");
    StyleConstants.setFontSize(attr, 12);
    StyleConstants.setBold(attr, true);
    StyleConstants.setBackground(attr, UIManager.getColor("control"));
    doc.insertString(1,str,attr);
    JTextPanel panel =new JTextPanel();
    panel.setEditorKit(kit);
    panel.setDocument(doc);
    text "hello word" of document can be show correctly,i save it as a .html file then open it a strange problem occured,i can't see the word "hello world" in panel,i can't find the word "hello word" in html source code except some tags of html,who can tell me what's wrong?thanks in advanced!

    hello user457523
    I have found the reason to that error.It's because there's a trigger and ext_src_file_nm is populated by the trigger from another column ext_src_file_loc when inserting and I didn't give any value to ext_src_file_loc so ext_src_file_nm is null.
    I have disabled that trigger and now I get new errors.When I traced to a line of Jave code I got missing source file warning,and the source file is also oracle.sql.CharacterSet.java.I can not trace into the source file and then I skipped that code and then I got new errors.I want to know how to trace into the jave code and find what's the matter.
    Thank you very much.

Maybe you are looking for

  • Can someone please help me with debugging these Lync client logs

    Hi, We have a mobile client on an Android device which is refusing to sign in. from the device you can browse to https://lyncdiscover.domain.com and also https://webext.domain.com/autodiscover/autodiscoverservice.svc/root and both times recvieve the

  • Af:setActionListener not working properly with resource bundle value

    Hi, I am making a ADF-BC JSF project in which I have a commit button a page. On click of this Commit button I am setting some value (Status) through setActionListener. But as this value(Status) is subject to change, so I have stored it in the resourc

  • Important URLs for Sun ONE Studio forums

    Check out our Sun ONE Studio forums by visiting the following links: For Java Tools: http://forte.sun.com/ffj/forums/index.html For Compiler Collection: http://forte.sun.com/s1scc/forums/index.html Add your voice to these active communities, while ga

  • How to make public distribution group to seend automated e-mails for acknowledgement

    My environment info : Exchange 2007 sp3 on Windows server 2008 R2sp1 ( Stand alone) I have a distribution group and i want to setup an automatic response have to be  sent to any sender to that distribution group (Like an acknowledgement e-mail statin

  • Viewing G1 RAWs as thumbnails in Organiser 9

    Hi, I think I'm correct in stating that I cannot view my Panasonic G1 RAWs as thumbnails in Organiser 9, as I can in SilkyPix which was supplied with my G1. I'm very impressed with Elements 9, but my G1 RAWs just show up as RAW icons. They open fine