Overflow JTextPane

I've got a task that I can't quite wrap my head around. I have a few thoughts on how to proceed but no sense of which idea might be better. I was hoping more experienced Swing developers might have some suggestions about these or better ways to proceed.
The task is to build a component which might look most like two stacked JTextPanes with a shared document. The top one would be editable, and would give a WYSIWYG view of their final output. The bottom one would be an overflow area. If the user types or pastes content that doesn't fit into the top one, it would automatically move to the bottom. There would be some kind of visual cue -- just the border, or a gray background area -- to distinguish for the users the content that won't show up in their final output from the content that will.
On another thread I posted the solutions I came up with for the first pass of this process: using a document that didn't let the user type or paste anything that would cause it to overflow the bounds of the JTextComponent holding it. (See http://forum.java.sun.com/thread.jsp?forum=57&thread=165787 if you are interested.) For the second pass I have to go a bit further and allow the user to actually enter this content, but give a visual clue about what portion of the content will be visible in the final format. The document will eventually be printed on a predefined area on a paper statement, so it cannot exceed certain bounds.
One approach I've considered is a filter on the StyledDocument, a class which implements the Document interface but which delegates all the adds, deletes, etc. to a StyleDocument member variable. One of these could somehow maintain its endpoint as a Position in its delegate. A second could use that same Position as its beginning. I have some sense of how this might work, but it is still a bit fuzzy.
Another approach would be to use a document for the top Textpane that, when something is added that will overflow the Textpane, removes the offending part and adds it to the beginning of the document in the bottom Textpane. Of course I would have to reverse this for deletes. I would have to do similar work when any characteristic is changed, e.g. font size. This strikes me as trickier to work than the first approach, and a lot more error-prone, but the way to do it is a little more clear in my head.
A third approach seems likely the best one, if I only knew something about how to implement it. If I understood Views and ViewFactories a bit better, I might be able to create different Views from the same document, one for the content that will fit in the required boundaries, and one for the remainder. Unfortunately, I haven't yet made much sense out of these classes. If anyone could supply a good reference, I would really appreciate it.
The final approach is outside the bounds of what I've so far done with Swing, but might actually not be that hard: Extend JTextPane in such a way that I can simply add a separator line at the bottom of the acceptable area. This just came to me now as I write this request, and I haven't had much time to consider it, but maybe this would make life much easier. Hmmm.
I would appreciate any feedback you can give about my suggested approaches or other ones I should consider.
Yours,
-- Scott Sauyet

I do have to get that book. Several people have recommended it. Someone on my recent project, after I sweated days over getting the first pass at this right, told me that the Topley book said that my preferred approach (I created several) was also the preferred approach given in this book. My answer was "Why didn't you tell me what was suggested in the book before I spent all this time?!"
And yes, I need to limit the real-estate occupied by the document. I don't care if it is two characters or two million, as long as it fits in a box of the right dimensions.
Thanks for the suggestion. Let me see if I can convince my boss to buy the book...
-- Scott

Similar Messages

  • SPOOL_INTERNAL_ERROR spool overflow when submitting the same program

    I am submitting the same program via job with different seletion screen values after JOB_OPEN, and then SUBMIT statement and JOB_CLOSE FM. But this job get cancelled with message "ABAP/4 processor: SPOOL_INTERNAL_ERROR" . The submit is as follows:
    SUBMIT (sy-repid) USER sy-uname
             VIA JOB 'ZTP_SAl_REG_MONITOR_JOBS'
             NUMBER l_jobcount
             TO SAP-SPOOL
             SPOOL PARAMETERS fp_user_print_params
              NEW LIST IDENTIFICATION 'X'
             WITHOUT SPOOL DYNPRO
             WITH rb_monit EQ 'X'
             WITH s_jobcnt IN s_jobcnt
             WITH p_date EQ p_date
             WITH rb_row EQ rb_row
             WITH rb_col EQ rb_col
             AND RETURN.
    Is it possible to use the same program to be scheduled....Let me include that the submit is happening with rb_monit = X and it has separate branch...so infinite looping can not happen.

    Hi Sumit,
    I hope that the flag is ensuring that it doesnt go into infinite loop. You may wish to check that once bcz Spool overflow seems to be bcz of infinite loop or bcz of layout issue.
    Goto SP01 in the same client where you have scheduled the job.
    Check the spool no. which was generated bcz of the job.
    Double click on the STATUS of the spool ( it should be in red background color).
    System will give a popup with status details.
    Again double click on the status. System will again give a popup.
    The popup will give the details of why the spool ran into errors.
    Also check the layout.
    Thanks,
    Best regards,
    Prashant

  • Overflow in the operation:= error

    Hi,
         I get the following error in my DTP of a process chain:
    Runtime error while executing rule -> see long text
    Diagnosis
    An error occurred while executing the transformation rule:
    The actual error message:
    Overflow in the operation :=
    The error was triggered at the following program location:
    System Response
    Processing of this data record was cancelled
    This issue seems to be because of the length of the target field being lesser than the source field.
    Can you please let me know how this issue can be resolved since the DTP is added in a process chain?
    Thanks in advance.

    Hi,
    As long as without knowing exact infoobject not easy to suggest direct solution.
    Assuming as your loading data from PSA to Cube.
    Go to your transformations, Menu Extras--> tabular overview, compare each source and target object length, need to be the same.
    if any target object length is lesser than source field , that length need to increased.
    Thanks

  • RUNTIME ERROR IN GENERATED PROGRAM. Overflow converting ''

    Hi,
    While executing the below code i am getting the error
    " RUNTIME ERROR IN GENERATED PROGRAM. Overflow converting ' ' am new to ABAP , can anyone kindly help me where i have went wrong ? .
    IF ( V_DO_CDS_NAME_MAIN <> '' ).
        ABAP.
            DATA: ref_it_tab TYPE REF TO data,
                  ref_wa TYPE REF TO data.
            FIELD-SYMBOLS: <fs_itab> TYPE ANY TABLE.
            FIELD-SYMBOLS: <fs_wa> TYPE ANY.
            FIELD-SYMBOLS: <fs_field> TYPE ANY.
            CREATE DATA ref_it_tab TYPE STANDARD TABLE OF (V_DO_CDS_NAME_MAIN) WITH NON-UNIQUE DEFAULT KEY.
            ASSIGN ref_it_tab->* TO <fs_itab>.
            SELECT * FROM (V_DO_CDS_NAME_MAIN) INTO TABLE <fs_itab> where C1 = V_WORK_ITEM_ID_MAIN.
            CREATE DATA ref_wa LIKE LINE OF <fs_itab>.
            ASSIGN ref_wa->* TO <fs_wa>.
            loop at <fs_itab> assigning <fs_wa>.
                assign component 'CLIENT' of structure <fs_wa> to <fs_field>.
                V_CLIENT = <fs_field>.
                assign component 'C0' of structure <fs_wa> to <fs_field>.
                V_C0 = <fs_field>.
                assign component 'C1' of structure <fs_wa> to <fs_field>.
                V_C1 = <fs_field>.
                assign component 'C2' of structure <fs_wa> to <fs_field>.
                V_C2 = <fs_field>.
                assign component 'C3' of structure <fs_wa> to <fs_field>.
                V_C3 = <fs_field>.
                assign component 'C4' of structure <fs_wa> to <fs_field>.
                V_C4 = <fs_field>.
                assign component 'C5' of structure <fs_wa> to <fs_field>.
                V_C5 = <fs_field>.
                assign component 'C6' of structure <fs_wa> to <fs_field>.
                V_C6 = <fs_field>.
                assign component 'C7' of structure <fs_wa> to <fs_field>.
                V_C7 = <fs_field>.
                assign component 'C8' of structure <fs_wa> to <fs_field>.
                V_C8 = <fs_field>.
                assign component 'MESSAGE_ID' of structure <fs_wa> to <fs_field>.
                V_MESSAGE_ID = <fs_field>.
                assign component 'TIMESTAMP' of structure <fs_wa> to <fs_field>.
                V_TIMESTAMP = <fs_field>.
                assign component 'EXTRACTKEY' of structure <fs_wa> to <fs_field>.
                V_EXTRACTKEY = <fs_field>.
                assign component 'STATEID' of structure <fs_wa> to <fs_field>.
                V_STATEID = <fs_field>.
                assign component 'DEVICE_ID' of structure <fs_wa> to <fs_field>.
                V_DEVICE_ID = <fs_field>.
            ENDLOOP.
        ENDABAP.
    ENDIF.

    Hi Mubeen,
    While Copying the cotes have come closer otherwise its working fine , i was able to find the error .
    There are ten predefined ABAP data types. There are 100 possible type combinations between these elementary data types. ABAP supports automatic type conversion and length adjustment for all of them except type D (date) and type T (time) fields which cannot be converted into each other.
    I commented the TimeStamp part where i had given the ABAP Type as D and it started working .
    But now i want to display the content of  "TimeStamp"  field but i am not able to do so .
    This is the format in which it has to be displayed 2009.011.915.3353.
    Which ABAPTYPE i need to use ?.
    i am able to display in this format 20090119153353
    regards
    Harsha

  • SAP paging overflow when storing data in the ABAP/4 memory.

    I am trying to create a data source in  BI7.0 in the Datawarehousing Workbench. But along the process when i need to select a view i get an error detailed in the following error file extract: Please go through and assist.
    untime Errors         MEMORY_NO_MORE_PAGING
    Date and Time          06.06.2009 14:21:35
    Short text
    SAP paging overflow when storing data in the ABAP/4 memory.
    What happened?
    The current program requested storage space from the SAP paging area,
    but this request could not be fulfilled.
    of this area in the SAP system profile.
    What can you do?
    Note which actions and input led to the error.
    For further help in handling the problem, contact your SAP administrator
    You can use the ABAP dump analysis transaction ST22 to view and manage
    termination messages, in particular for long term reference.
    Error analysis
    The ABAP/4 runtime system and the ABAP/4 compiler use a common
    interface to store different types of data in different parts of
    the SAP paging area. This data includes the
    ABAP/4 memory (EXPORT TO MEMORY), the SUBMIT REPORT parameters,
    CALL DIALOG and CALL TRANSACTION USING, as well as internally defined
    macros (specified with DEFINE).
    To store further data in the SAP paging area, you attempted to
    allocate a new SAP paging block, but no more blocks were
    available.
    When the SAP paging overflow occurred, the ABAP/4 memory contained
    entries for 20 of different IDs.
    Please note:
    To facilitate error handling, the ABAP/4 memory was
    deleted.
    How to correct the error
    The amount of storage space (in bytes) filled at termination time was:
    Roll area...................... 8176
    Extended memory (EM)........... 13587912
    Assigned memory (HEAP)......... 0
    Short area..................... " "
    Paging area.................... 40960
    Maximum address space.......... " "
    By calling Transaction SM04 and choosing 'Goto' -> 'Block list',
    you can display an overview of the current roll and paging memory
    levels resulting from active users and their transactions. Try to
    decide from this whether another program requires a lot of memory
    space (perhaps too much).
    The system log contains more detailed information about the
    termination. Check for any unwanted recursion.
    Determine whether the error also occurs with small volumes of
    data. Check the profile (parameter "rdisp/PG_MAXFS", see
    Installation Guidelines).
    Is the disk or the file system that contains the paging file
    full to the extent that it cannot be increased, although it has
    not yet reached the size defined in the profile? Is the
    operating system configured to accommodate files of such a
    size?
    The ABAP processor stores different types of data in the SAP
    paging area. These include:
    (1) Data clusters (EXPORT ... TO MEMORY ...)
    (2) Parameters for calling programs (SUBMIT REPORT ...),
    Dialog modules (CALL DIALOG ...) and transactions
    (CALL TRANSACTION USING ...)
    (3) Internally defined program macros (DEFINE ...)
    Accordingly, you should check the relevant statements in a program
    that results in an overflow of the SAP paging area.
    It is critical when many internal tables, possibly with
    different IDs, are written to memory (EXPORT).
    If the error occures in a non-modified SAP program, you may be able to
    find an interim solution in an SAP Note.
    If you have access to SAP Notes, carry out a search with the following
    keywords:
    "MEMORY_NO_MORE_PAGING" " "
    "SAPLWDTM" or "LWDTMU20"
    "TABC_ACTIVATE_AND_UPDATE"
    If you cannot solve the problem yourself and want to send an error
    notification to SAP, include the following information:
    1. The description of the current problem (short dump)
    To save the description, choose "System->List->Save->Local File
    (Unconverted)".
    2. Corresponding system log
    Display the system log by calling transaction SM21.
    Restrict the time interval to 10 minutes before and five minutes
    after the short dump. Then choose "System->List->Save->Local File
    (Unconverted)".
    3. If the problem occurs in a problem of your own or a modified SAP
    program: The source code of the program
    In the editor, choose "Utilities->More
    Utilities->Upload/Download->Download".
    4. Details about the conditions under which the error occurred or which
    actions and input led to the error.

    Hi Huggins,
    Maintenance of the Paging File is owned by your basis team.
    They should increase this in order for your transaction to process successfully.
    Just for your reference, in case the OS used is windows server 2003, paging file value can be checked through;
    Right click in the My Computer&gt;properties.
    Then go to Advance tab;
    Then there should be a performance section, click the settings
    Then Advance tab again. The paging file can be seen from there.
    (and can be adjusted from there also)
    The value of the paging file in general will be dependent with the available RAM from the hardware.
    Hope this helps. Thanks a lot.
    - Jeff

  • Cannot Send Email from Crystal Reports Viewer; MAPI:Overflow

    I am trying to send a report via email with crystal reports, but i get the following error message:
    "The following unexpected error occured while trying to send the report to MAPI: Overflow."
    I am using Outlook 2010, Win 7 x64 bit.
    Does anyone have any ideas or thoughts?

    Yes, it is a 3rd party app that opens Crystal Reports Viewer.  Attached are the screen shots I get when try to send the report as an email.
    -Dan

  • ComponentView does not redraw component in JTextPane Cell Rend

    We have created a JTable implementation that uses JTextPanes as cell renderers/editors so that text styles and the like are available. We want insert a component, such as a JButton, into the JTextPane. However, the component is only visible when the cell is in an editable state. In the renderer, the ComponentView looks like it has set aside the space where the component is to be, but the component is not visible.
    I have looked at this problem for several days now, and have only determined that this seems to be occuring at a low level. What I have found is that the ButtonUI's update method is not called when the document is in the cell renderer, while it seems called continuously in the cell editor (on each caret blink).
    Does anybody have any insight as to the problem? I have submitted this as a bug to Sun but wanted to find out if anybody else has come across anything similar to this.
    Thank for any help.
    Steve Feveile
    Here is sample code to reproduce the problem:
    // Main Class
    * Main frame for the testing of the component not painting. This simplifies
    * an issue we have come across when trying to set up using a JTextPane as a
    * renderer/editor as the cells in a table.
    * Under these conditions we have found that a component inserted into the JTextPanes document
    * only appears in the editing state of the cell, whereas the rendering state leaves
    * the spacing for the component but does not make it visible.
    * Note that creating a JTextPane with the one of these documents will show the component,
    * even when not editing.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class tableFrame extends JFrame
         public tableFrame()
              //set up frame
              getContentPane().setLayout(new BorderLayout());
              setSize(500,300);
              setTitle("Table Missing Component Test");
    addWindowListener(
         new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                             setVisible(false);                         
                   System.exit(0);     
              //set up components the table
              JTable table = new JTable(createDocumentTableModel(2,2));
              table.setRowHeight(60);
              //set the default renderer/editor to use the JTextPane implementation
              for (int x = 0; x < table.getColumnCount(); x++) {
                   table.setDefaultEditor(table.getColumnClass(x), new TextPaneCellEditor());
                   table.setDefaultRenderer(table.getColumnClass(x), new TextPaneRenderer());
              JScrollPane pane = new JScrollPane(table);
              getContentPane().add(pane, BorderLayout.CENTER);
              //this adds a textpane without the table involved
              //uising the same way of inserting a document
              JTextPane tPane = new JTextPane();
              DefaultStyledDocument doc = new DefaultStyledDocument();
              try
                   doc.insertString(0, "Some text in a JTextPane", null);
                   JButton b = new JButton("Button");
         SimpleAttributeSet inputAttributes = new SimpleAttributeSet();
              StyleConstants.setComponent(inputAttributes, b);
              doc.insertString(0 , " ", inputAttributes);
              catch (Throwable t)
                   System.out.println("createDocumentTableModel error: " + t.getMessage());
              tPane.setDocument(doc);
              tPane.setSize(490, 60);
              JScrollPane pane2 = new JScrollPane(tPane);
              getContentPane().add(pane2, BorderLayout.SOUTH);
         * this creates a table model where the documents are the value
         * in each cell, and the cell renderer/editor can use this instead
         * of a string value
         private TableModel createDocumentTableModel(int row, int col)
              Vector headerData = new Vector();
              Vector tableData = new Vector();
              for (int i=0;i<row;i++)
                   headerData.add("Column" + i);
                   Vector rowData = new Vector();
                   for (int j=0;j<col;j++)
                        DefaultStyledDocument doc = new DefaultStyledDocument();
                        try
                             //this inserts some string to see that this is visible
                             //when editing and rendering
                             doc.insertString(0, ("Row: " + i + ", Column: " + j), null);
                             //this button will only be visible when the cell is in
                             //an editing state
                             JButton b = new JButton("Button" + i + "-" + j);
                   SimpleAttributeSet inputAttributes = new SimpleAttributeSet();
                        StyleConstants.setComponent(inputAttributes, b);
                        doc.insertString(0 , " ", inputAttributes);
                        catch (Throwable t)
                             System.out.println("createDocumentTableModel error: " + t.getMessage());
                        rowData.add(doc);
                   tableData.add(rowData);
              return new DefaultTableModel(tableData, headerData);
         //starts the ball rolling
         static public void main(String args[])
              (new tableFrame()).setVisible(true);
    // Custom Cell Editor
    * Sets the editor to use a JTextPane implementation
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.util.EventObject;
    import java.io.Serializable;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneCellEditor implements TableCellEditor
    /** Event listeners */
    protected EventListenerList listenerList = new EventListenerList();
    transient protected ChangeEvent changeEvent = null;
    protected JTextPane editorComponent;
    protected EditorDelegate delegate;
    protected int clickCountToStart = 1;
         * constructor.
    public TextPaneCellEditor() {
              editorComponent = new JTextPane();
              //use 1 click count to edit a cell
              clickCountToStart = 1;
              * controls the values of the editor
              delegate = new EditorDelegate() {
                   * sets the text value cell.
                   * @param value - value to set in the document
                   public void setValue(Object value) {
                        if (value instanceof Document)
                             editorComponent.setDocument((Document) value);
                        else
                             editorComponent.setText("");
                   * gets the text value cell.
                   * @return the document in the textpane
                   public Object getCellEditorValue() {
                        return editorComponent.getDocument();
         // implements the setting the value for the editor
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
              if (value != null)          
                   delegate.setValue(value);
              else
                   delegate.setValue("");
              return editorComponent;
    // Implementing the CellEditor Interface
         // implements javax.swing.CellEditor
         public Object getCellEditorValue() {
              return delegate.getCellEditorValue();
         // implements javax.swing.CellEditor
         public boolean isCellEditable(EventObject anEvent) {
              if (anEvent instanceof MouseEvent) {
                   return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
              return true;
    // implements javax.swing.CellEditor
         public boolean shouldSelectCell(EventObject anEvent) {
              return delegate.shouldSelectCell(anEvent);
         // implements javax.swing.CellEditor
         public boolean stopCellEditing() {
              fireEditingStopped();
              return true;
         // implements javax.swing.CellEditor
         public void cancelCellEditing() {
              fireEditingCanceled();
    // Handle the event listener bookkeeping
         // implements javax.swing.CellEditor
         public void addCellEditorListener(CellEditorListener l) {
              listenerList.add(CellEditorListener.class, l);
         // implements javax.swing.CellEditor
         public void removeCellEditorListener(CellEditorListener l) {
              listenerList.remove(CellEditorListener.class, l);
         * Notify all listeners that have registered interest for
         * notification on this event type. The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @see EventListenerList
         protected void fireEditingStopped() {
              // Guaranteed to return a non-null array
              Object[] listeners = listenerList.getListenerList();
              // Process the listeners last to first, notifying
              // those that are interested in this event
              for (int i = listeners.length-2; i>=0; i-=2) {
                   if (listeners==CellEditorListener.class) {
                        // Lazily create the event:
                        if (changeEvent == null)
                             changeEvent = new ChangeEvent(this);
                        ((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
         * Notify all listeners that have registered interest for
         * notification on this event type. The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @see EventListenerList
         protected void fireEditingCanceled() {
              // Guaranteed to return a non-null array
              Object[] listeners = listenerList.getListenerList();
              // Process the listeners last to first, notifying
              // those that are interested in this event
              for (int i = listeners.length-2; i>=0; i-=2) {
                   if (listeners[i]==CellEditorListener.class) {
                        // Lazily create the event:
                        if (changeEvent == null)
                             changeEvent = new ChangeEvent(this);
                        ((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
    // Protected EditorDelegate class
    protected class EditorDelegate implements ActionListener, ItemListener, Serializable {
              //made up of unimplemented methods
              protected Object value;
              public Object getCellEditorValue() {
                   return null;
              public void setValue(Object x) {}
              public void setDocument(Object x) {}
              public Document getDocument() {
                   return null;
              public boolean isCellEditable(EventObject anEvent) {
                   return true;
              /** Unfortunately, restrictions on API changes force us to
              * declare this method package private.
              boolean shouldSelectCell(EventObject anEvent) {
                   return true;
              public boolean startCellEditing(EventObject anEvent) {
                   return true;
              public boolean stopCellEditing() {
                   return true;
                   public void cancelCellEditing() {
              public void actionPerformed(ActionEvent e) {
                   fireEditingStopped();
              public void itemStateChanged(ItemEvent e) {
                   fireEditingStopped();
    // Custom Cell Renderer
    * renders a table cell as a JTextPane.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TextPaneRenderer extends JTextPane implements TableCellRenderer                                                  
         * Constructor - just set to noneditable
         public TextPaneRenderer() {
              setEditable(false);
         * implementation of table cell renderer. If the value is a document
         * the, the text panes setDocument is used, otherwise a string value
         * is set
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
              if (value != null)
                   if (value instanceof Document)
                        //set the value to a document
                        setDocument((Document) value);
                   else
                        //convert the value to a string
                        setText(value.toString());
              else
                   //set text to an empty string
                   setText("");
              return this;

    Hi, I came across the forum and found your problem is very similar to what I am having now. Your post has been a year old, I just wonder if you come up anything productive to what you had? Could you let us know what you (or Sun) find out if you do have one? Thanks.

  • Problem with JTextPane and StateInvariantError

    Hi. I am having a problem with JTextPanes and changing only certain text to bold. I am writing a chat program and would like to allow users to make certain text in their entries bold. The best way I can think of to do this is to add <b> and </b> tags to the beginning and end of any text that is to be bold. When the other client receives the message, the program will take out all of the <b> and </b> tags and display any text between them as bold (or italic with <i> and </i>). I've searched the forums a lot and figured out several ways to make the text bold, and several ways to determine which text is bold before sending the text, but none that work together. Currently, I add the bold tags with this code: (note: messageDoc is a StyledDocument and messageText is a JTextPane)
    public String getMessageText() {
              String text = null;
              boolean bold = false, italic = false;
              for (int i = 0; i < messageDoc.getLength(); i++) {
                   messageText.setCaretPosition(i);
                   if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && !bold) {
                        bold = true;
                        if (text != null) {
                             text = text + "<b>";
                        else {
                             text = "<b>";
                   else if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold) {
                        // Do nothing
                   else if (!StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold) {
                        bold = false;
                        if (text != null) {
                             text = text + "</b>";
                        else {
                             text = "</b>";
                   try {
                        if (text != null) {
                             text = text + messageDoc.getText(i,1);
                        else {
                             text = messageDoc.getText(i, 1);
                   catch (BadLocationException e) {
                        System.out.println("An error occurred while getting the text from the message document");
                        e.printStackTrace();
              return text;
         } // end getMessageText()When the message is sent to the other client, the program searches through the received message and changes the text between the bold tags to bold. This seems as if it should work, but as soon as I click on the bold button, I get a StateInvariantError. The code for my button is:
    public void actionPerformed(ActionEvent evt) {
              if (evt.getSource() == bold) {
                   MutableAttributeSet bold = new SimpleAttributeSet();
                   StyleConstants.setBold(bold, true);
                   messageText.getStyledDocument().setCharacterAttributes(messageText.getSelectionStart(), messageText.getSelectionStart() - messageText.getSelectionEnd() - 1, bold, false);
         } //end actionPerformed()Can anyone help me to figure out why this error is being thrown? I have searched for a while to figure out this way of doing what I'm trying to do and I've found out that a StateInvariantError has been reported as a bug in several different circumstances but not in relation to this. Or, if there is a better way to add and check the style of the text that would be great as well. Any help is much appreciated, thanks in advance.

    Swing related questions should be posted in the Swing forum.
    Can't tell from you code what the problem is because I don't know the context of how each method is invoked. But it would seem like you are trying to query the data in the Document while the Document is being updated. Try wrapping the getMessageText() method is a SwingUtilities.invokeLater().
    There is no need to write custom code for a Bold Action you can just use:
    JButton bold = new JButton( new StyledEditorKit.BoldAction() );Also your code to build the text String is not very efficient. You should not be using string concatenation to append text to the string. You should be using a StringBuffer or StringBuilder.

  • 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

  • Short Dump : Page Overflow

    Hi All,
    When i am executing a report on Production, i am getting short dump - "Page overflow".
    It's very urgent.
    Early response will be highly appreciated.
    Best regards,

    Can you provide more details?
    From what it looks like, i think your basis should increase the memory allocations for your internal tables.
    Regards,
    Ravi

  • ALV Report - Field Overflow message in status Bar

    Hi
    I am trying to display ALV report , ALV report is displaying fine but on execution of report , an message in status bar is coming as "Field copy Number can not be totalled because of field overflow."
    Can anyone tell why such messgae is comming?
    Thanks,
    Debadatta

    Just a wild guess, treat the below as an example.
    Eg:
    assuming one field in the output is of length 2 type i.
    values: 20, 30, 60, 45.
    Totalling the values result as 155. but due to the length of the field as 2. We can encounter the overflow message.
      Considering the above example, manually total the values of your numerical columns and see if any of the column is execeeding the specified length.
    Regards
    Eswar
    Note: Reward if you find the info useful.

  • XMLTRANSFORM Too large stylesheet - code buffer overflow issue

    Hi All,
    My question is related to MSWordML generation from PLSQL stored procedure.
    1. I have table, containing XSLT stylesheets for different documents
    2. PLSQL stored procedure is generating dynamic content depending on some params and at the end I'm using
    SELECT XMLTRANSFORM(XMLTYPE.createxml(db_data_clob), XMLTYPE.createxml(x.xslt_clob)).GetClobVal()
    INTO   res
    FROM   msword_ml_data x
    WHERE  x.report_id = rep_id_variable;
    where : x.xslt_clob -> column, containing XSLT CLOB
    db_data_clob -> dynamic content CLOB
    res -> CLOB result
    All this was working fine on Oracle11gR1, but I had to reinstall database and I said why not install Oracle11gR2 ...
    Guess what. Stored procedure is raising exception when using XMLTRANSFORM :
    Exception : : ORA-31011: XML parsing failed
    ORA-19202: Error occurred in XML processing
    LPX-00004: internal error "Too large stylesheet - code buffer overflow"
    Google says nothing about it. I don't recall setting some special DB property in Oracle11gR1.
    Has anyone encountered this ?
    I haven't changed procedure nor table.
    I'm using exactly the same XSLT's from Java code and they are working just fine, so they are not the reason. My guess is that something in Oracle11gR2 related to XML processing is changed.
    If anyone could help, thanks in advance

    For those who are interested.
    I have logged a service request and it turned out that this is is a bug in Oracle 11gR2.
    "The limitation on the style sheet is not exactly a size limit but a limitation on the number of style sheet instructions and depends on the way the style sheet has been written. This is a C based parser limitation"
    Anyway, the workaround is to create Java stored procedure and do transformation from there.

  • Multi-document Application using JTextPane - Issue

    Hi.
    I'm making a java IDE as a class assignment where the user opens a certain project and all associated files open (i.e. all files in the requested folder). Opening is not an issue but here's the real problem. When a file opens (in the JTextPane), the user should be able to edit it. Although my program enables this, what also happens is that if the user switches onto viewing another file (i.e. clicking a file name from a tree in the file pane) the previously open file obviously closes and nothing is saved. I don't want to save the users edits in the actual file until and unless the user themselves click save, but 'd like the application to store the intermediate state of documents until a save request or until the program is terminated. Is there any easy way of doing this?
    Thanks.

    {color:#000080}Cross posting.{color}
    http://forum.java.sun.com/thread.jspa?threadID=5217794&tstart=0
    {color:#000080}Cross posting is rude.
    db{color}

  • Questions on in-memory with disk based overflow cache.

    Hi, support
    I want to create a cache which have two tiers, one is size limited local cache and the other uses a disk as a storage. As you said if the local cache is full, the other data will be moved to external cache (on disk). Does it mean the other data will be saved in a temp file? If so, could you let me know where is temp file? The config file is attached.
    Btw, although I used on disk cache as a external cache, I got Exception in thread "main" java.lang.OutOfMemoryError: Java heap space also when I put lots of data into the cache.
    Thanks a lot.
    <?xml version="1.0"?>
    <!DOCTYPE cache-config SYSTEM "cache-config.dtd">
    <cache-config>
         <caching-scheme-mapping>
                        <!-- this local cache is used for buffer in rdsprocessor -->
              <cache-mapping>
                   <cache-name>bufferStorage</cache-name>
                   <scheme-name>SampleOverflowScheme</scheme-name>
              </cache-mapping>
         </caching-scheme-mapping>
         <caching-schemes>
              <overflow-scheme>
                   <scheme-name>           
                        SampleOverflowScheme
                   </scheme-name>
                   <front-scheme>
                        <local-scheme>
                             <high-units>100</high-units>
                        </local-scheme>
                   </front-scheme>
                   <back-scheme>
                        <external-scheme>
                             <lh-file-manager/>
                             <!--
                             <high-units>10</high-units>
                             -->
                        </external-scheme>
                   </back-scheme>
              </overflow-scheme>           
         </caching-schemes>
    </cache-config>
    Message was edited by:
    user620684

    Hi, Jon
    Thanks for your help.
    I will use an unconfigured LH file manager(I mean the file path and name will not be specified.).
    Currently, find the temp file will be created in C:\Documents and Settings\$user_name\Local Settings\Temp in windows.
    I have two questions on temp file.
    1) Does tangosol supply a mechanism to maintain the temp files?
    2) In solaris, which place will the temp file be created in?
    Thanks,
    Bin
    null

  • How to prevent JTextPane from inserting newline on setText(longLine)

    Hi all, I have seen some posts (referenced below) regarding
    JTextPane and turning off line wrap. I tried these but still
    have some unwanted behavior.
    If I insert long html content that has no CRs in it into a JTextPane,
    using setText(...)
    and then immediatly call getText()
    I get back my html content with CRs in it.
    how can I prevent this????
    In the code below, I insert a long line (html), then call getText()
    and JTextPane has inserted a CR after the ffff
    visually , in the gui, it did not put a line break there, which is great, but
    somewhere in the document model it was inserted
    I have code that would break if there are newlines in
    strange places like that.
    I DO want the html markup from the call to JTextPane.getText()
    but not with the additional newlines.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.text.html.*;
    import javax.swing.text.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.awt.datatransfer.*;
    public class MyTextPane extends JTextPane implements MouseListener, ActionListener {
           static final long serialVersionUID = 1;
           private JPopupMenu popupMenu = null;
           private JMenuItem  cutMenuItem = null;
           private JMenuItem  copyMenuItem = null;
           private JMenuItem  pasteMenuItem = null;
           private JMenuItem  clearMenuItem = null;
           //private JMenuItem  selectAllMenuItem = null;
           private int startSelectionPosition = -1;
           private int endSelectionPosition = -1;
           private boolean bTopSeperatorInserted = false;
           private int topMenuItemInsertionIndex = 0;
           public MyTextPane() {
             super();
             init();
           private void init() {
             addMouseListener(this);
             java.awt.Font font = new java.awt.Font("Dialog", java.awt.Font.PLAIN, 14);
             setFont(font);
             createAndConfigurePopupMenu();
             startNewDocument();
             A FocusListener is also added to our editor. The two methods of this listener, focusGained() and
             focusLost(), will be invoked when the editor gains and loses the focus respectively. The purpose of
             this implementation is to save and restore the starting and end positions of the text selection.
             The reason? -> Swing supports only one text selection at any given time. This means
             that if the user selects some text in the editor component to modify it's attributes, and then goes
             off and makes a text selection in some other component, the original text selection will disappear.
             This can potentially be very annoying to the user. To fix this problem I'll save the selection before
             the editor component loses the focus. When the focus is gained we restore the previously saved selection.
             I'll distinguish between two possible situations: when the caret is located at the beginning of the
             selection and when it is located at the end of the selection. In the first case, position the
             caret at the end of the stored interval with the setCaretPosition() method, and then move the
             caret backward to the beginning of the stored interval with the moveCaretPosition() method.
             The second situation is easily handled using the select() method.
             FocusListener focusListener = new FocusListener() {
               public void focusGained(FocusEvent e) {
                 int len = getDocument().getLength();
                 if (startSelectionPosition>=0 &&
                     endSelectionPosition>=0 &&
                     startSelectionPosition<len &&
                     endSelectionPosition<len)
                   if (getCaretPosition() == startSelectionPosition) {
                     setCaretPosition(endSelectionPosition);
                     moveCaretPosition(startSelectionPosition);
                   else
                     select(startSelectionPosition, endSelectionPosition);
               public void focusLost(FocusEvent e) {
                 startSelectionPosition = getSelectionStart();
                 endSelectionPosition = getSelectionEnd();
             addFocusListener(focusListener);
             // CONTROL+ALT+S to view HTML source and change it
             Action viewSourceAction = new ViewSourceAction();
             getActionMap().put("viewSourceAction", viewSourceAction);
             InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
             KeyStroke keyStroke = KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S,
                                                     InputEvent.CTRL_MASK+InputEvent.ALT_MASK);
             inputMap.put(keyStroke, "viewSourceAction");
           // if a merge tag is at the end of a long line, JTextPane
           // inserts CR/LF into the middle of the merge tag, like this
           // "this is a really long line and at the end is a merge tag <merge \r\n name="Case ID"/>"
           // We need to turn off line wrapping to prevent this.
           // see http://forum.java.sun.com/thread.jspa?forumID=57&threadID=326017
           // overriding setSize(..) and getScrollableTracksViewportWidth()
           public void setSize(Dimension d)
               if (d.width < getParent().getSize().width)
                   d.width = getParent().getSize().width;
               super.setSize(d);
           public boolean getScrollableTracksViewportWidth() { return false; }
           class ViewSourceAction extends AbstractAction
             public void actionPerformed(ActionEvent e)
               try {
                 HTMLEditorKit m_kit = (HTMLEditorKit)MyTextPane.this.getEditorKit();
                 HTMLDocument m_doc = (HTMLDocument)MyTextPane.this.getDocument();
                 StringWriter sw = new StringWriter();
                 m_kit.write(sw, m_doc, 0, m_doc.getLength());
                 sw.close();
                 HtmlSourceDlg dlg = new HtmlSourceDlg(null, sw.toString());
                 dlg.setVisible(true);
                 if (!dlg.succeeded())
                   return;
                 StringReader sr = new StringReader(dlg.getSource());
                 m_doc = createDocument();
                 m_kit.read(sr, m_doc, 0);
                 sr.close();
                 setDocument(m_doc);
               catch (Exception ex) {
                 ex.printStackTrace();
           private HTMLDocument createDocument() {
             HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
             StyleSheet styles = htmlEditorKit.getStyleSheet();
             StyleSheet ss = new StyleSheet();
             ss.addStyleSheet(styles);
             HTMLDocument doc = new HTMLDocument(ss);
             //doc.setParser(htmlEditorKit.getParser());
             //doc.setAsynchronousLoadPriority(4);
             //doc.setTokenThreshold(100);
             return doc;
           public Element getElementByTag(HTML.Tag tag) {
             HTMLDocument htmlDocument = (HTMLDocument)getDocument();
             Element root = htmlDocument.getDefaultRootElement();
             return getElementByTag(root, tag);
           public Element getElementByTag(Element parent, HTML.Tag tag) {
             if (parent == null || tag == null)
               return null;
             for (int k=0; k<parent.getElementCount(); k++) {
               Element child = parent.getElement(k);
               if (child.getAttributes().getAttribute(
                   StyleConstants.NameAttribute).equals(tag))
                 return child;
               Element e = getElementByTag(child, tag);
               if (e != null)
                 return e;
             return null;
           public void mouseClicked(MouseEvent e){}
           public void mouseEntered(MouseEvent e){}
           public void mouseExited(MouseEvent e){}
           public void mouseReleased(MouseEvent e){}
           public void mousePressed(MouseEvent e)
             if (e.getModifiers() == MouseEvent.BUTTON3_MASK)
               Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
               if (cb.getContents(this) == null || !isEditable() || !isEnabled()) {
                 pasteMenuItem.setEnabled(false);
               } else {
                 pasteMenuItem.setEnabled(true);
               if (getSelectedText() == null) {
                 copyMenuItem.setEnabled(false);
                 cutMenuItem.setEnabled(false);
               } else {
                 copyMenuItem.setEnabled(true);
                 if ((getBorder() == null) || !isEditable() || !isEnabled()) {
                   cutMenuItem.setEnabled(false);
                 } else {
                   cutMenuItem.setEnabled(true);
               popupMenu.show(this,e.getX(),e.getY());
           public JPopupMenu getPopupMenu() { return popupMenu; }
            * Creates the Popup menu with Cut,Copy,Paste
            * menu items if it hasn't already been created.
           private void createAndConfigurePopupMenu() {
             popupMenu = new JPopupMenu();
             clearMenuItem = new JMenuItem(new ClearAction());
             clearMenuItem.setText("Clear");
             //selectAllMenuItem = new JMenuItem(new SelectAllAction());
             //selectAllMenuItem.setText("Select All");
             cutMenuItem = new JMenuItem(new DefaultEditorKit.CutAction());
             cutMenuItem.setText("Cut");
             copyMenuItem = new JMenuItem(new DefaultEditorKit.CopyAction());
             copyMenuItem.setText("Copy");
             // when pasting, only paste the plain text (not any markup)
             PasteAction pasteAction = new PasteAction();
             pasteMenuItem = new JMenuItem(/*new DefaultEditorKit.PasteAction()*/);
             pasteMenuItem.addActionListener(pasteAction);
             pasteMenuItem.setText("Paste");
             popupMenu.add(cutMenuItem);
             popupMenu.add(copyMenuItem);
             popupMenu.add(pasteMenuItem);
             popupMenu.add(new JPopupMenu.Separator());
             popupMenu.add(clearMenuItem);
             //popupMenu.add(selectAllMenuItem);
             setKeyStrokes();
           private void doPasteAction()
               Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
               Transferable content = cb.getContents(this);
               try {
                   // when pasting, discard the markup
                   String s = (String)content.getTransferData(DataFlavor.stringFlavor);
                   HTMLDocument doc = (HTMLDocument)MyTextPane.this.getDocument();
                   HTMLEditorKit kit = (HTMLEditorKit)MyTextPane.this.getEditorKit();
                   doc.insertString(MyTextPane.this.getCaretPosition(),
                                    s,
                                    kit.getInputAttributes());
               catch (Throwable exc) {
                   exc.printStackTrace();
           class PasteAction implements ActionListener
               public void actionPerformed(ActionEvent e) {
                   doPasteAction();
            * Sets the short cut keys and actions for corresponding actions for keys.
           private void setKeyStrokes() {
               KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
                                                        KeyEvent.CTRL_MASK);
               /** Performs pasteAction when short-cut key paste action is performed */
               Action pasteAction = new AbstractAction() {
                    * Handles user clicked actions.
                    * @param actionEvent -
                    *            ActionEvent object.
                   public void actionPerformed(ActionEvent actionEvent) {
                       doPasteAction();
               InputMap inputMap = getInputMap(JTextPane.WHEN_FOCUSED);
               getActionMap().put(inputMap.get(paste), pasteAction);
           public void actionPerformed(ActionEvent e) {
              if(e.getActionCommand().equals("Select All"))
                selectAll();
              else if(e.getActionCommand().equals("Clear"))
                clear();
           public void append(String s) {
             super.setText( getText() + s );
           public void clear() {
             startNewDocument();
           public void startNewDocument() {
             HTMLEditorKit editorKit = new HTMLEditorKit();
             setContentType("text/html");
             setEditorKit(editorKit);
             HTMLDocument document = (HTMLDocument) editorKit.createDefaultDocument();
             setDocument(document);
             // to enable the copy and paste from ms word (and others) to the JTextPane, set
             // this client property. Sun Bug ID: 4765240
             document.putProperty("IgnoreCharsetDirective",Boolean.TRUE);
             document.setPreservesUnknownTags(false);
           class ClearAction extends AbstractAction{
             public void actionPerformed(ActionEvent e) {
               startNewDocument();
           class SelectAllAction extends AbstractAction{
             public void actionPerformed(ActionEvent e) {
               selectAll();
           class HtmlSourceDlg extends JDialog {
             protected boolean m_succeeded = false;
             protected JTextArea m_sourceTxt;
             public HtmlSourceDlg(JFrame parent, String source) {
               super(parent, "HTML Source", true);
               JPanel pp = new JPanel(new BorderLayout());
               pp.setBorder(new EmptyBorder(10, 10, 5, 10));
               m_sourceTxt = new JTextArea(source, 20, 60);
               m_sourceTxt.setFont(new Font("Courier", Font.PLAIN, 12));
               JScrollPane sp = new JScrollPane(m_sourceTxt);
               pp.add(sp, BorderLayout.CENTER);
               JPanel p = new JPanel(new FlowLayout());
               JPanel p1 = new JPanel(new GridLayout(1, 2, 10, 0));
               JButton bt = new JButton("Save");
               ActionListener lst = new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                   m_succeeded = true;
                   dispose();
               bt.addActionListener(lst);
               p1.add(bt);
               bt = new JButton("Cancel");
               lst = new ActionListener() {
                 public void actionPerformed(ActionEvent e) {
                   dispose();
               bt.addActionListener(lst);
               p1.add(bt);
               p.add(p1);
               pp.add(p, BorderLayout.SOUTH);
               getContentPane().add(pp, BorderLayout.CENTER);
               pack();
               setResizable(true);
               setLocationRelativeTo(parent);
             public boolean succeeded() {
               return m_succeeded;
             public String getSource() {
               return m_sourceTxt.getText();
           public void addToPopupMenuAboveEditItems(JMenuItem menuItem)
             if (!bTopSeperatorInserted) {
               popupMenu.insert(new JPopupMenu.Separator(), 0);
               bTopSeperatorInserted = true;
             popupMenu.insert(menuItem, topMenuItemInsertionIndex);
             ++topMenuItemInsertionIndex;
           public static void main(String args[])
             JFrame frame = new JFrame("MyTextPane");
             MyTextPane textPane = new MyTextPane();
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             JScrollPane scrollPane = new JScrollPane(textPane);        
             String s = "<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbb cccc dddd eeee ffff gggg hhhh iiii jjjj aaaaaaaaaaaaaaaaaaaaaaa</p>";        
             System.out.println("\nthe long string prior to calling JTextPane.setText(..) WITH NO NEWLINES\ns=" +s);
             textPane.setText(s);
             System.out.println("\n\nthe text returned from calling JTextPane.setText(..) -> it inserted CR & newline after the ffff\n");
             System.out.println("textPane.getText()=" +textPane.getText());
             frame.getContentPane().add(scrollPane,BorderLayout.CENTER);
             frame.setSize(500, 700);
             frame.setVisible(true);
         }http://forum.java.sun.com/thread.jspa?threadID=356749&messageID=3012080
    and
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=326017
    Edited by: henryhamster on Sep 13, 2007 8:59 PM

    ok, I found a somewhat work around. calling JTextPane.getText() eventually
    invokes HTMLEditorKit.write()
    which does code
    HTMLWriter w = new HTMLWriter(out, (HTMLDocument)doc, pos, len);
    w.write();the HTMLWriter() constructor above makes this call
    setLineLength(80);
    So If I extend some classes (JEditorKit and HTMLWriter) I can call invoke
    htmlWriter.setLineLength(1000); // ridiculous length to prevent insertion of CR/LF
    here is the hack, can someone please tell
    me there is an easier way. :-)
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.text.html.*;
    import javax.swing.text.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.awt.datatransfer.*;
    public class MyTextPane extends JTextPane implements MouseListener,
              ActionListener {
         static final long serialVersionUID = 1;
         private JPopupMenu popupMenu = null;
         private JMenuItem cutMenuItem = null;
         private JMenuItem copyMenuItem = null;
         private JMenuItem pasteMenuItem = null;
         private JMenuItem clearMenuItem = null;
         // private JMenuItem selectAllMenuItem = null;
         private int startSelectionPosition = -1;
         private int endSelectionPosition = -1;
         private boolean bTopSeperatorInserted = false;
         private int topMenuItemInsertionIndex = 0;
         public MyTextPane() {
              super();
              init();
         private void init() {
              addMouseListener(this);
              java.awt.Font font = new java.awt.Font("Dialog", java.awt.Font.PLAIN,
                        14);
              setFont(font);
              createAndConfigurePopupMenu();
              startNewDocument();
               * A FocusListener is also added to our editor. The two methods of this
               * listener, focusGained() and focusLost(), will be invoked when the
               * editor gains and loses the focus respectively. The purpose of this
               * implementation is to save and restore the starting and end positions
               * of the text selection. The reason? -> Swing supports only one text
               * selection at any given time. This means that if the user selects some
               * text in the editor component to modify it's attributes, and then goes
               * off and makes a text selection in some other component, the original
               * text selection will disappear. This can potentially be very annoying
               * to the user. To fix this problem I'll save the selection before the
               * editor component loses the focus. When the focus is gained we restore
               * the previously saved selection. I'll distinguish between two possible
               * situations: when the caret is located at the beginning of the
               * selection and when it is located at the end of the selection. In the
               * first case, position the caret at the end of the stored interval with
               * the setCaretPosition() method, and then move the caret backward to
               * the beginning of the stored interval with the moveCaretPosition()
               * method. The second situation is easily handled using the select()
               * method.
              FocusListener focusListener = new FocusListener() {
                   public void focusGained(FocusEvent e) {
                        int len = getDocument().getLength();
                        if (startSelectionPosition >= 0 && endSelectionPosition >= 0
                                  && startSelectionPosition < len
                                  && endSelectionPosition < len) {
                             if (getCaretPosition() == startSelectionPosition) {
                                  setCaretPosition(endSelectionPosition);
                                  moveCaretPosition(startSelectionPosition);
                             } else
                                  select(startSelectionPosition, endSelectionPosition);
                   public void focusLost(FocusEvent e) {
                        startSelectionPosition = getSelectionStart();
                        endSelectionPosition = getSelectionEnd();
              addFocusListener(focusListener);
              // CONTROL+ALT+S to view HTML source and change it
              Action viewSourceAction = new ViewSourceAction();
              getActionMap().put("viewSourceAction", viewSourceAction);
              InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              KeyStroke keyStroke = KeyStroke.getKeyStroke(
                        java.awt.event.KeyEvent.VK_S, InputEvent.CTRL_MASK
                                  + InputEvent.ALT_MASK);
              inputMap.put(keyStroke, "viewSourceAction");
         // if a merge tag is at the end of a long line, JTextPane
         // inserts CR/LF into the middle of the merge tag, like this
         // "this is a really long line and at the end is a merge tag <merge \r\n
         // name="Case ID"/>"
         // We need to turn off line wrapping to prevent this.
         // see http://forum.java.sun.com/thread.jspa?forumID=57&threadID=326017
         // overriding setSize(..) and getScrollableTracksViewportWidth()
         public void setSize(Dimension d) {
              if (d.width < getParent().getSize().width)
                   d.width = getParent().getSize().width;
              super.setSize(d);
         public boolean getScrollableTracksViewportWidth() {
              return false;
         class ViewSourceAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   try {
                        HTMLEditorKit m_kit = (HTMLEditorKit) MyTextPane.this
                                  .getEditorKit();
                        HTMLDocument m_doc = (HTMLDocument) MyTextPane.this
                                  .getDocument();
                        StringWriter sw = new StringWriter();
                        m_kit.write(sw, m_doc, 0, m_doc.getLength());
                        sw.close();
                        HtmlSourceDlg dlg = new HtmlSourceDlg(null, sw.toString());
                        dlg.setVisible(true);
                        if (!dlg.succeeded())
                             return;
                        StringReader sr = new StringReader(dlg.getSource());
                        m_doc = createDocument();
                        m_kit.read(sr, m_doc, 0);
                        sr.close();
                        setDocument(m_doc);
                   } catch (Exception ex) {
                        ex.printStackTrace();
         private HTMLDocument createDocument() {
              HTMLEditorKit htmlEditorKit = new HTMLEditorKit();
              StyleSheet styles = htmlEditorKit.getStyleSheet();
              StyleSheet ss = new StyleSheet();
              ss.addStyleSheet(styles);
              HTMLDocument doc = new HTMLDocument(ss);
              // doc.setParser(htmlEditorKit.getParser());
              // doc.setAsynchronousLoadPriority(4);
              // doc.setTokenThreshold(100);
              return doc;
         public Element getElementByTag(HTML.Tag tag) {
              HTMLDocument htmlDocument = (HTMLDocument) getDocument();
              Element root = htmlDocument.getDefaultRootElement();
              return getElementByTag(root, tag);
         public Element getElementByTag(Element parent, HTML.Tag tag) {
              if (parent == null || tag == null)
                   return null;
              for (int k = 0; k < parent.getElementCount(); k++) {
                   Element child = parent.getElement(k);
                   if (child.getAttributes()
                             .getAttribute(StyleConstants.NameAttribute).equals(tag))
                        return child;
                   Element e = getElementByTag(child, tag);
                   if (e != null)
                        return e;
              return null;
         public void mouseClicked(MouseEvent e) {
         public void mouseEntered(MouseEvent e) {
         public void mouseExited(MouseEvent e) {
         public void mouseReleased(MouseEvent e) {
         public void mousePressed(MouseEvent e) {
              if (e.getModifiers() == MouseEvent.BUTTON3_MASK) {
                   Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
                   if (cb.getContents(this) == null || !isEditable() || !isEnabled()) {
                        pasteMenuItem.setEnabled(false);
                   } else {
                        pasteMenuItem.setEnabled(true);
                   if (getSelectedText() == null) {
                        copyMenuItem.setEnabled(false);
                        cutMenuItem.setEnabled(false);
                   } else {
                        copyMenuItem.setEnabled(true);
                        if ((getBorder() == null) || !isEditable() || !isEnabled()) {
                             cutMenuItem.setEnabled(false);
                        } else {
                             cutMenuItem.setEnabled(true);
                   popupMenu.show(this, e.getX(), e.getY());
         public JPopupMenu getPopupMenu() {
              return popupMenu;
          * Creates the Popup menu with Cut,Copy,Paste menu items if it hasn't
          * already been created.
         private void createAndConfigurePopupMenu() {
              popupMenu = new JPopupMenu();
              clearMenuItem = new JMenuItem(new ClearAction());
              clearMenuItem.setText("Clear");
              // selectAllMenuItem = new JMenuItem(new SelectAllAction());
              // selectAllMenuItem.setText("Select All");
              cutMenuItem = new JMenuItem(new DefaultEditorKit.CutAction());
              cutMenuItem.setText("Cut");
              copyMenuItem = new JMenuItem(new DefaultEditorKit.CopyAction());
              copyMenuItem.setText("Copy");
              // when pasting, only paste the plain text (not any markup)
              PasteAction pasteAction = new PasteAction();
              pasteMenuItem = new JMenuItem(/* new DefaultEditorKit.PasteAction() */);
              pasteMenuItem.addActionListener(pasteAction);
              pasteMenuItem.setText("Paste");
              popupMenu.add(cutMenuItem);
              popupMenu.add(copyMenuItem);
              popupMenu.add(pasteMenuItem);
              popupMenu.add(new JPopupMenu.Separator());
              popupMenu.add(clearMenuItem);
              // popupMenu.add(selectAllMenuItem);
              setKeyStrokes();
         private void doPasteAction() {
              Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
              Transferable content = cb.getContents(this);
              try {
                   // when pasting, discard the markup
                   String s = (String) content
                             .getTransferData(DataFlavor.stringFlavor);
                   HTMLDocument doc = (HTMLDocument) MyTextPane.this.getDocument();
                   HTMLEditorKit kit = (HTMLEditorKit) MyTextPane.this.getEditorKit();
                   doc.insertString(MyTextPane.this.getCaretPosition(), s, kit
                             .getInputAttributes());
              } catch (Throwable exc) {
                   exc.printStackTrace();
         class PasteAction implements ActionListener {
              public void actionPerformed(ActionEvent e) {
                   doPasteAction();
          * Sets the short cut keys and actions for corresponding actions for keys.
         private void setKeyStrokes() {
              KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
                        KeyEvent.CTRL_MASK);
              /** Performs pasteAction when short-cut key paste action is performed */
              Action pasteAction = new AbstractAction() {
                    * Handles user clicked actions.
                    * @param actionEvent -
                    *            ActionEvent object.
                   public void actionPerformed(ActionEvent actionEvent) {
                        doPasteAction();
              InputMap inputMap = getInputMap(JTextPane.WHEN_FOCUSED);
              getActionMap().put(inputMap.get(paste), pasteAction);
         public void actionPerformed(ActionEvent e) {
              if (e.getActionCommand().equals("Select All"))
                   selectAll();
              else if (e.getActionCommand().equals("Clear"))
                   clear();
         public void append(String s) {
              super.setText(getText() + s);
         public void clear() {
              startNewDocument();
         public void startNewDocument() {
              MyHTMLEditorKit editorKit = new MyHTMLEditorKit();
              setContentType("text/html");
              setEditorKit(editorKit);
              HTMLDocument document = (HTMLDocument) editorKit
                        .createDefaultDocument();
              setDocument(document);
              // to enable the copy and paste from ms word (and others) to the
              // JTextPane, set
              // this client property. Sun Bug ID: 4765240
              document.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
              document.setPreservesUnknownTags(false);
         class ClearAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   startNewDocument();
         class SelectAllAction extends AbstractAction {
              public void actionPerformed(ActionEvent e) {
                   selectAll();
         class HtmlSourceDlg extends JDialog {
              protected boolean m_succeeded = false;
              protected JTextArea m_sourceTxt;
              public HtmlSourceDlg(JFrame parent, String source) {
                   super(parent, "HTML Source", true);
                   JPanel pp = new JPanel(new BorderLayout());
                   pp.setBorder(new EmptyBorder(10, 10, 5, 10));
                   m_sourceTxt = new JTextArea(source, 20, 60);
                   m_sourceTxt.setFont(new Font("Courier", Font.PLAIN, 12));
                   JScrollPane sp = new JScrollPane(m_sourceTxt);
                   pp.add(sp, BorderLayout.CENTER);
                   JPanel p = new JPanel(new FlowLayout());
                   JPanel p1 = new JPanel(new GridLayout(1, 2, 10, 0));
                   JButton bt = new JButton("Save");
                   ActionListener lst = new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             m_succeeded = true;
                             dispose();
                   bt.addActionListener(lst);
                   p1.add(bt);
                   bt = new JButton("Cancel");
                   lst = new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             dispose();
                   bt.addActionListener(lst);
                   p1.add(bt);
                   p.add(p1);
                   pp.add(p, BorderLayout.SOUTH);
                   getContentPane().add(pp, BorderLayout.CENTER);
                   pack();
                   setResizable(true);
                   setLocationRelativeTo(parent);
              public boolean succeeded() {
                   return m_succeeded;
              public String getSource() {
                   return m_sourceTxt.getText();
         public void addToPopupMenuAboveEditItems(JMenuItem menuItem) {
              if (!bTopSeperatorInserted) {
                   popupMenu.insert(new JPopupMenu.Separator(), 0);
                   bTopSeperatorInserted = true;
              popupMenu.insert(menuItem, topMenuItemInsertionIndex);
              ++topMenuItemInsertionIndex;
         public static void main(String args[]) {
              JFrame frame = new JFrame("MyTextPane");
              MyTextPane textPane = new MyTextPane();
              HTMLDocument doc = (HTMLDocument) textPane.getDocument();
              HTMLEditorKit kit = (HTMLEditorKit) textPane.getEditorKit();
              StringWriter buf = new StringWriter();
              // MyHTMLWriter w = new MyHTMLWriter(buf, (HTMLDocument) doc, 0,
              // doc.getLength());
              // w.setLineLength(150);
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JScrollPane scrollPane = new JScrollPane(textPane);
              String s = "<p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbb cccc dddd eeee ffff gggg hhhh iiii jjjj aaaaaaaaaaaaaaaaaaaaaaa</p>";
              System.out
                        .println("\nthe long string prior to calling JTextPane.setText(..) WITH NO NEWLINES\ns="
                                  + s);
              textPane.setText(s);
              String sOut = textPane.getText();
              System.out
                        .println("\n\nthe text returned from calling JTextPane.setText(..) -> it inserted CR & newline after the ffff\n");
              System.out.println("textPane.getText()=" + sOut);
              frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
              frame.setSize(500, 700);
              frame.setVisible(true);
    class MyHTMLWriter extends HTMLWriter {
         public MyHTMLWriter(Writer buf, HTMLDocument doc, int pos, int len) {
              super(buf, doc, pos, len);
         protected void setLineLength(int l) {
              super.setLineLength(l);
    class MyHTMLEditorKit extends HTMLEditorKit {
         public void write(Writer out, Document doc, int pos, int len)
                   throws IOException, BadLocationException {
              if (doc instanceof HTMLDocument) {
                   MyHTMLWriter w = new MyHTMLWriter(out, (HTMLDocument) doc, pos, len);
                   w.setLineLength(200);
                   w.write();
              } else if (doc instanceof StyledDocument) {
                   MinimalHTMLWriter w = new MinimalHTMLWriter(out,
                             (StyledDocument) doc, pos, len);
                   w.write();
              } else {
                   super.write(out, doc, pos, len);
    }and

Maybe you are looking for

  • Help please! itunes wont open

    i am using a windows XP and my itunes will not open. I have uninstalled and reinstalled itunes and quicktime numerous times and itunes will still not open. Quicktime opens fine. I have also opened my Task Manager and itunes appear under processes but

  • Need Help in Oracle Service Contracts API -- OKS_COVERAGES_PUB

    Hi All We have a requirement in service contracts module, wherein we have to delete the old coverage template of service line of a contract and attach the new template with the service line. For this, we are using OKS_COVERAGES_PUB ("OKS_COVERAGES_PU

  • How do you string integers together?

    I have the task of creating a program that will give you the resistance in ohms based on the color bands on the resistor. (This is a problem for a Labview course I am taking) I know this program could be done a lot more efficiently but I am still a b

  • DHTML Date Picker (Calendar)

    I recently ran across a thread that linked to Guido Zeelen's DHTML date picker. The code for this calendar can be found here: http://htmldb.oracle.com/pls/otn/f?p=18326:54:::::P54_ID:2102 I have downloaded the files mentioned, but the directions are

  • Start Up Failure: Due to windows 8 update Interrupted ?

    Hi   Yesterday i got windows update but at that time my battery is not even half charge. However, my system started taking updates and mean will my laptop battery got discharge completely. Today when i am trying to start the laptop it is showing me b