Is it a JTextPane's bug?

I wrote some test code as below:
public class TTextComponents {
     public static void main(String[] args) {
//          final JEditorPane editorPane = new JEditorPane();
          final JTextPane textPane = new JTextPane();
          final JButton btn = new JButton("open");
          btn.addActionListener(new ActionListener()
                         /* (non-Javadoc)
                          * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
                         public void actionPerformed(ActionEvent e) {
                              JFileChooser fc = new JFileChooser();
                              int ret =fc.showOpenDialog(btn);
                              if(ret == JFileChooser.APPROVE_OPTION)
                                   try {
//                                        editorPane.setPage(fc.getSelectedFile().toURL());
                                        textPane.setPage(fc.getSelectedFile().toURL());
//                                        printEditorPane(editorPane);
                                        printEditorPane(textPane);
                                   } catch (MalformedURLException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
                                   } catch (IOException e1) {
                                        // TODO Auto-generated catch block
                                        e1.printStackTrace();
//          printEditorPane(editorPane);
          printEditorPane(textPane);
          JPanel mainPane = new JPanel(new GridLayout(1,2));
//          mainPane.add(editorPane);
          mainPane.add(textPane);
          JFrame frame = new JFrame("JFrame Test!");
          Container c = frame.getContentPane();
          c.setLayout(new BorderLayout());
          c.add(btn,BorderLayout.NORTH);
          c.add(mainPane,BorderLayout.CENTER);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setVisible(true);
          printEditorPane(textPane);
     private static void printEditorPane(JEditorPane pane)
          System.out.println(pane +" is:");
          System.out.println("model is: "+pane.getDocument());
          System.out.println("editorkit is: "+pane.getEditorKit());
          System.out.println("content type is: "+pane.getContentType());
          System.out.println("\n");
}now i use the button to open a non- plaintext file firstly, then open a plain-text, IllegalArgumentException was thrown.
I debug into the code, found if content-type was changed, JTextPane use javax.swing.JEditorPane$PlainEditorKit as plaintext's EditorKit, but it only accept StyledEditorKit.

Hi Gowri,
We have also faced the same issue. for the data we are showing in measure tab in pivot table changed into Show Data as -> Percentage of -> Column is showing correct percentage data in pivot table. But if we are taking 'chart Pivoted Results' the chart is showing only the value not percentage.
Result: Only '*Pie*' chart work with solution and show same percentage in the pie chart view. In bar, line and other chart results will not display the expected result.
Hope it helps.
Regards,
Pandian

Similar Messages

  • JTextPane StyledDocument insertString multi Icon problem (BUG?)

    Hi,
    Now I am trying to insert some icons to the StyledDocument of JTextPane.
    I found a problem that if I want to insert the same Icon (actually the same style which contains this icon) into the StyledDocument for more than one time, only the first insert operation works.
    But if I insert a whitespace (or other non-zero length text) between the twe icon, it can works. I don't know it's my mis-using of this StyledDocument or it's a bug of JTextPane and StyledDocument?
    Thanks!
    My sample code below: To Run this code, you need to add a "icon" named "t1.jpg" in your project directory ^_^
    import java.awt.BorderLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    public class JTextPaneInsertIcons
         public static void main(String[] args) throws Exception
              JTextPane pane = new JTextPane();
              ImageIcon icon = new ImageIcon("t1.jpg");
              StyledDocument styledDocument = pane.getStyledDocument();
              Style iconStyle = styledDocument.addStyle("icon", null);
              StyleConstants.setIcon(iconStyle, icon);
              styledDocument.insertString(styledDocument.getLength(), " ", iconStyle);
              styledDocument.insertString(styledDocument.getLength(), " ", iconStyle);
              styledDocument.insertString(styledDocument.getLength(), "\n", StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
              styledDocument.insertString(styledDocument.getLength(), " ", iconStyle);
              styledDocument.insertString(styledDocument.getLength(), " ", StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
              styledDocument.insertString(styledDocument.getLength(), " ", iconStyle);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add(pane, BorderLayout.CENTER);
              frame.setSize(360, 180);
              frame.setVisible(true);
    }

    OK, OK, I got it.
    Thank you so much!
    It seems I need to solve this problem ugly like this:
    import java.awt.BorderLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JTextPane;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.Element;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    public class JTextPaneInsertIcons
         static StyledDocument styledDocument;
         public static void main(String[] args) throws Exception
              JTextPane pane = new JTextPane();
              ImageIcon icon = new ImageIcon("1.jpg");
              styledDocument = pane.getStyledDocument();
              Style iconStyle = styledDocument.addStyle("icon", null);
              StyleConstants.setIcon(iconStyle, icon);
              insertOne(iconStyle);
              insertOne(iconStyle);
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add(pane, BorderLayout.CENTER);
              frame.setSize(600, 400);
              frame.setVisible(true);
         private static void insertOne(Style style) throws Exception
              if (style.getAttribute(StyleConstants.IconAttribute) != null)
                   if (styledDocument.getLength() > 0)
                        Element e = styledDocument.getCharacterElement(styledDocument.getLength() - 1);
                        AttributeSet attributeSet = e.getAttributes();
                        if (style.getAttribute(StyleConstants.IconAttribute) == attributeSet
                                  .getAttribute(StyleConstants.IconAttribute))
                             styledDocument.insertString(styledDocument.getLength(), " ", StyleContext
                                       .getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE));
              styledDocument.insertString(styledDocument.getLength(), " ", style);
    }

  • JTextPane bug?

    Oddly enough, when I insert a string with a style of an image into a JTextPane more than once, it only adds the first one.
    doc.insertString(doc.getLength(), " ",txtResponses.getStyle("pigImage"));
    doc.insertString(doc.getLength(), " ",txtResponses.getStyle("pigImage"));
    // The JTextPane only inserts the first image.On the other hand...
    doc.insertString(doc.getLength(), " ",txtResponses.getStyle("pigImage"));
    doc.insertString(doc.getLength(), " ",txtResponses.getStyle("birdImage"));
    // The JTextPane inserts the first and second image.Why does it do that?
    Is there a fix or is this a bug?

    I see, thanks. I thought that it would place it infront since I specifiyed doc.getLength() which should have been larger after inserting the first image.
    But anyways I worked around this with a simple trick. If the image to be inserted is the same, then before inserting the new image I insert a null.gif image inbetween. The null.gif is a 1 pixel transparent image. So the users don't even see any difference.
    Thanks.

  • Bug in JTextArea/JTextPane ??

    Hi,
    I am facing huge memory leak problems with JTextArea/JTextPane. After considerable investigation, I found out that the Document associated with the component is not being GC'ed properly. I ran OptimizeIt and found out that the memory is being consumed by the JTextPane.setText() method. I have implmented a HTML viewer to display large amounts of HTML data and it is leaking memory like crazy on each successive execution. Any thoughts ??
    JDK1.4.2_01, WinXP
    Here is the code fragment:
    public class ReportViewer extends BaseFrame implements FontChange_int
         private     String          cReport;          
         private boolean          testMode = false;     
         // Graphical components
         private     BorderLayout     cMainLayout;
         private     JButton          cClose;
         private     JTextPane     cRptPane;
         private     Button          cClose2;
         private ViewUpdater cViewUpdater = null;
         // Constants
         final     static     int     startupXSize = 650;
         final     static     int     startupYSize = 500;
         // Methods
         public ReportViewer(String report, ReportMain main)
              // BaseFrame extends JFrame
              super("Reports Viewer", true, startupXSize, startupYSize);
              testMode = false;
              cReport = report;
              cViewUpdater = new ViewUpdater();
              initialize();
         public void initialize()
              // Create main layout manager
              cMainLayout = new BorderLayout();
              getContentPane().setLayout(cMainLayout);
              // Quick button bar - print, export, save as
              JToolBar     topPanel = new JToolBar();
              topPanel.setBorder(new BevelBorder(BevelBorder.RAISED) );
              java.net.URL     url;
              topPanel.add(Box.createHorizontalStrut(10));
              url = Scm.class.getResource("images/Exit.gif");
              cClose = new Button(new ImageIcon(url), true);
              cClose.setToolTipText("Close Window");
              topPanel.add(cClose);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              // Main view window - HTML
              cRptPane = new JTextPane();
              cRptPane.setContentType("text/html");
              cRptPane.setEditable(false);
              JScrollPane sp = new JScrollPane(cRptPane);
              getContentPane().add(sp, BorderLayout.CENTER);
              // Main button - Close
              JPanel     bottomPanel = new JPanel();
              url = Scm.class.getResource("images/Exit.gif");
              cClose2 = new Button(new ImageIcon(url), "Close");
              bottomPanel.add(cClose2);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              cClose.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              cClose2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              show();
              cViewUpdater.setText(cReport);
              SwingUtilities.invokeLater(cViewUpdater);
         protected void
         closeWindow()
              super.closeWindow();
              // If I add the following lines, the GC reclaims
    // part of the memory but does not flush out the text
    // component as a whole
              /*Document doc = cRptPane.getDocument();
              try
                   doc.remove(0,doc.getLength());
              catch(Exception e) {;}
              doc=null; */
              cRptPane=null;
              cReport = null;
              cViewUpdater = null;
              dispose();
         private class ViewUpdater implements Runnable
              private String cText = null;
              public ViewUpdater() {;}
              public void
              setText(String text) {
                   cText = text;
              public void
              run() {
                   cRptPane.setText(cText);
                   cRptPane.setCaretPosition(0);
                   cText = null;
         // Local main - for testing
         public static void main(String args[])
              //new ReportViewer(str,comp);
    Sudarshan
    www.spectrumscm.com

    Hi,
    I am facing huge memory leak problems with JTextArea/JTextPane. After considerable investigation, I found out that the Document associated with the component is not being GC'ed properly. I ran OptimizeIt and found out that the memory is being consumed by the JTextPane.setText() method. I have implmented a HTML viewer to display large amounts of HTML data and it is leaking memory like crazy on each successive execution. Any thoughts ??
    JDK1.4.2_01, WinXP
    Here is the code fragment:
    public class ReportViewer extends BaseFrame implements FontChange_int
         private     String          cReport;          
         private boolean          testMode = false;     
         // Graphical components
         private     BorderLayout     cMainLayout;
         private     JButton          cClose;
         private     JTextPane     cRptPane;
         private     Button          cClose2;
         private ViewUpdater cViewUpdater = null;
         // Constants
         final     static     int     startupXSize = 650;
         final     static     int     startupYSize = 500;
         // Methods
         public ReportViewer(String report, ReportMain main)
              // BaseFrame extends JFrame
              super("Reports Viewer", true, startupXSize, startupYSize);
              testMode = false;
              cReport = report;
              cViewUpdater = new ViewUpdater();
              initialize();
         public void initialize()
              // Create main layout manager
              cMainLayout = new BorderLayout();
              getContentPane().setLayout(cMainLayout);
              // Quick button bar - print, export, save as
              JToolBar     topPanel = new JToolBar();
              topPanel.setBorder(new BevelBorder(BevelBorder.RAISED) );
              java.net.URL     url;
              topPanel.add(Box.createHorizontalStrut(10));
              url = Scm.class.getResource("images/Exit.gif");
              cClose = new Button(new ImageIcon(url), true);
              cClose.setToolTipText("Close Window");
              topPanel.add(cClose);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              // Main view window - HTML
              cRptPane = new JTextPane();
              cRptPane.setContentType("text/html");
              cRptPane.setEditable(false);
              JScrollPane sp = new JScrollPane(cRptPane);
              getContentPane().add(sp, BorderLayout.CENTER);
              // Main button - Close
              JPanel     bottomPanel = new JPanel();
              url = Scm.class.getResource("images/Exit.gif");
              cClose2 = new Button(new ImageIcon(url), "Close");
              bottomPanel.add(cClose2);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              cClose.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              cClose2.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        closeWindow();
              show();
              cViewUpdater.setText(cReport);
              SwingUtilities.invokeLater(cViewUpdater);
         protected void
         closeWindow()
              super.closeWindow();
              // If I add the following lines, the GC reclaims
    // part of the memory but does not flush out the text
    // component as a whole
              /*Document doc = cRptPane.getDocument();
              try
                   doc.remove(0,doc.getLength());
              catch(Exception e) {;}
              doc=null; */
              cRptPane=null;
              cReport = null;
              cViewUpdater = null;
              dispose();
         private class ViewUpdater implements Runnable
              private String cText = null;
              public ViewUpdater() {;}
              public void
              setText(String text) {
                   cText = text;
              public void
              run() {
                   cRptPane.setText(cText);
                   cRptPane.setCaretPosition(0);
                   cText = null;
         // Local main - for testing
         public static void main(String args[])
              //new ReportViewer(str,comp);
    Sudarshan
    www.spectrumscm.com

  • 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 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

  • Saving RTF from JTextPane and missing subscripts

    I've written a little application that involves saving and loading styled text in a JTextPane. Bold and italic styled text survives the loading/saving process but subscripts always revert to the regular style.
    To test this further, I created a document with bold, italic and subscript styled text in MS Word, saved it as RTF and then loaded it into my JTextPane. I got the same result as above: my subscripts were lost, but bold and italic survived.
    Is this a bug? If so any news of it being known or fixed?
    thanks,
    McN

    Swing's RTFEditorKit only supports an early release of the RTF specification -- maybe somewhere along 1.1. Microsoft has updated the spec with each new version of Word, so that I think the XP version is something around 1.6 or 1.7. The most common behavior of the current Swing RTFEditorKit is to ignore those extra features it doesn't recognize, like subscripts, tables, images, etc. I have occasionally had it produce a null value as well...giving me fits.

  • JTextPane and the default PasteAction

    Now here's a really bad problem. I'm writing a custom word processor in Java (isn't everyone?). I'm using a JTextPane, with an assigned HTMLEditorKit and an assigned HTMLDocument. Code as shown below:
        this.vHtmlPane = new JTextPane();
        this.vHtmlKit = new HTMLEditorKit();
        this.vHtmlPane.setLayout(new BorderLayout());
        this.vHtmlPane.setEditorKit(this.vHtmlKit);
        this.vHtmlDoc = new HTMLDocument();
        this.vHtmlPane.setDocument(this.vHtmlDoc);
        this.vHtmlDoc.addUndoableEditListener(this.vUndoMgr);So far so good. Now, following all the documentation I could find, setting up cut and paste is as easy as the following:
        JMenu mEdit = new JMenu("Edit");
        mEdit.add(this.getActionByName(this.vHtmlKit.cutAction));
        mEdit.add(this.getActionByName(this.vHtmlKit.copyAction));
        mEdit.add(this.getActionByName(this.vHtmlKit.pasteAction));Where getActionByName() is implemented from:
      private void createActionTable(HTMLEditorKit htmlKit) {
        this.vActionMap = new HashMap();
        Action[] actions = htmlKit.getActions();
        for(int i = 0; i<actions.length; i++) {
          Action a = actions;
    this.vActionMap.put(a.getValue(Action.NAME),a);
    private Action getActionByName(String name) {
    return (Action)(this.vActionMap.get(name));
    The problem is when I go to paste something using ctrl-v (I'm developing on WinXP). I get an IllegalArgumentException followed by a whole lot of nullpointers and then everything goes to hell. My work machine just hangs, and my home machine reboots. The circumstances are like so:
    ctrl-c from Textpad or Notetabpro or any true text editor - works fine.
    ctrl-c from Mozilla or anything that adds anything remotely like html code to the clipboard - hell in a handbasket.
    I've traced the problem through several levels of the core JDK, and it seems that all the screaming starts in the TransferHandler classes importData(JComponent comp, Transferable t) method. Something about that and the interaction with the HTMLDocument trying to handle the import of html tags. Beyond that I'm kinda stumped. I would have thought that the default behaviour for an HTMLDocument paste would be to url-encode incoming text, but it seems that it pastes it wholesale, at which point the HTMLDocument refreshes and chokes on the tags it did not generate.
    I would appreciate any insight into how to override the default paste action or even better, how to fix it so the default paste action stops blowing up the app. I'd write my own default paste action without bothering the luminaries on this board, but after diving several levels into the EditorKit and finding such things as Flavor and Transferable classes and a PasteAction married to the EditorKit class... it just seemed like I must be missing the trick somehow.
    The particulars:
    Jdk: Sun 1.4.2_04
    IDE: JBuilder X patch 3
    WinXP sans the e-vile SP2 (so I'm on SP1)
    Anyone have any ideas?

    A little more background...
    I traced a paste event all the way through, and I'm getting the fatal error at line 231 in HTMLEditorKit:
        public void read(Reader in, Document doc, int pos) throws IOException, BadLocationException {
         if (doc instanceof HTMLDocument) {
             HTMLDocument hdoc = (HTMLDocument) doc;
             Parser p = getParser();
             if (p == null) {
              throw new IOException("Can't load parser");
             if (pos > doc.getLength()) {
              throw new BadLocationException("Invalid location", pos);
             ParserCallback receiver = hdoc.getReader(pos);
             Boolean ignoreCharset = (Boolean)doc.getProperty("IgnoreCharsetDirective");
             p.parse(in, receiver, (ignoreCharset == null) ? false : ignoreCharset.booleanValue());
             receiver.flush();
         } else {
             super.read(in, doc, pos);
        }Line 231 is the receiver.flush() call, at which point a RuntimeException is thrown and caught at line 212 in the EventDispatchThread class pumpOneEventForHierarchy method.
    C'mon guys - this has got to be a bug! I traced while pasting some text from Notepad and that went fine. Then I pasted from Mozilla, and got the above. I can't see the state of the objects in the core Java classes (can't seem to get JBuilder to show that), but that's what's happening.
    I'm going to hit post on this now, and then stop runtime debugging on JBuilder and watch my computer reboot. Can anyone shed some light on this???

  • Word wrapping incorrect inside JTextPane on MAC 0.5/10.4 and Linux OS

    Hello java-dev team,
    In my application, I am using JTextPane as a text editor to create RTF text. The problem I observed with the JTextPane on MAC OS and Linux OS flavors (I tested on Ubuntu 8.04) is: whenever I am changing any of the text property (font color, font name, font style like bold, italic or underline) and then enter the characters without providing space, the whole word gets wrapped to the next line from the point where exactly the property change starts i.e. the new formatted text is jumped to the next line from the starting point of formatting.
    My requirement is, as I am not adding any space character while changing the property, the characters should be entered in the sequence and should come to new line as per normal word-wrap rule.
    Can anybody help me out in this regards with some solution as it’s a very urgent requirement?
    Below I am also providing the sample code to check the behavior. There is no dynamic facility to change the property in the below code but I am providing the text with multiple formatting settings through code itself. To reproduce the above issue, just type the characters using keyboard in between characters with changed text properties and you can see the whole word jumping to new line.
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class TestWrapping {
         JScrollPane scroll;
         JTextPane edit;
         public TestWrapping()  throws Exception {
              final JFrame frame=new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              edit=new JTextPane()
                   public void setSize(Dimension d)
                        if (d.width < getParent().getSize().width)
                             d.width = getParent().getSize().width;
                        super.setSize(d);
                   public boolean getScrollableTracksViewportWidth()
                        return false;
              edit.setPreferredSize(new Dimension(150,150));
              edit.setSize(150,150);
              edit.setEditorKit(new StyledEditorKit());
              scroll=new JScrollPane(edit);
              edit.getDocument().insertString(0,"11111111111111222222222222222222222222222222222222222",null);
              MutableAttributeSet attrs=new SimpleAttributeSet();
              StyleConstants.setBold(attrs,true);
              ((StyledDocument)edit.getDocument()).setCharacterAttributes(30,5,attrs,false);
              StyleConstants.setUnderline(attrs,true);
              ((StyledDocument)edit.getDocument()).setCharacterAttributes(35,5,attrs,false);
              StyleConstants.setFontSize(attrs,25);
              ((StyledDocument)edit.getDocument()).setCharacterAttributes(40,5,attrs,false);
              frame.getContentPane().add(scroll);
              frame.setBounds(0,0,150,150);
              frame.show();
         public static void main(String[] args) throws Exception {
              new TestWrapping();
    }The same functionality works fine on Windows XP and problem is observed on MAC OS 10.4/10.5, Ubuntu 8.04. I am using jdk1.5 on both the platforms. I tested using jdk 6.0 on Ubuntu 8.04, and the problem is easily reproducible. I placed a query in the respective OS forums also but did not receive any replies. I also searched the sun’s bug database, but could not find any bug addressing the mentioned problem correctly. I also logged issue at bugs.sun.com and was assigned internal review ID of 1480019 for this problem.
    If you need any additional information, please let me know.
    Thanks in advance.
    Regards,
    VPKVL

    VPKVL wrote:
    Hi All,
    Just want to update that when I checked this issue with JDK1.6 on Ubuntu 8.04, I am unable to reproduce the issue. Everything works as expected. But problem continues on MAC 10.5. So can anybody help me out in coming out of this issue on MAC 10.5.
    Thanks in advance.The only thing I can suggest is that you open a bug (radar) with apple ( developer.apple.com ), and then wait at least 12 months for Apple to get around to fixing it :s

  • 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'

  • Scrolling to a given line or offset  in a JTextPane   *Please Help*

    I have looked on the web and do not see a solution to this problem. Maybee I am missing somthing very easy here.
    I am using a JTextPane to display text of multiple colours.
    The JTextPane is contained within a JScrollPane.
    I am using a highlighter to highlight individual lines of text within this JTextPane.
    However, the highlighted text may be outside of the viewport of the scrollPane and not be visible.
    How do I scroll so that the highlighted line of code is visible????
    I know you can scrollToVisibleRect. However how do I get the rectangle coordinates from a line of code, or from the highlighter.
    Is it possibile and easy to scroll to make an offset or line number visible.????
    So far I have tried:
    setCaretPosition();
    However this causes problems with highlighting.
    Cheers
    Andrew.

    In the future, Swing related questions should be posted in the Swing forum.
    So far I have tried:
    setCaretPosition();
    However this causes problems with highlighting.Makes no sense, setting the caret position has nothing to do with highlighting. Sounds like you have some other bug. Setting the caret position should work.
    I know you can scrollToVisibleRect. However how do I get the
    rectangle coordinates from a line of code, or from the highlighterAssuming you know the offset of the text you can use
    textPane.modelToView(...)
    to get the location of the text.

  • Is caret positioning in right-to-left oriented jtextpane corruptable?

    Dear all -
    Below is a serious problem. I hope I can get help from you experts out there; otherwise, I think it is a bug that should be reported to the JDK developers.
    I am writing an editor using my own keyboard layout to type in Arabic. To do so, I use jTextPane, and my own implementation of DocumentFilter (where I map English keys to Arabic letters). I start by i) setting the component orientation of jTextPane to be from RIGHT_TO_LEFT, and ii) attaching a caretListener to trace the caret's position.
    The problem (I think it is a bug just like what is recorded here: http://bugs.adobe.com/jira/browse/SDK-16315):
    Initially as I type text in Arabic, there is one-to-one correspondence between where I point my mouse and where the caret displays, basically, the same place. However, a problem occurs (and can always be re-produced) when I type a word towards the end of the line, follow it by a space character, and that space character causes the word to descend to the next line as a result of a wrap-around. Now, as I point my mouse to that first line again, the location where I click the mouse and the location where the caret flashes are no longer coincident! Also, the caret progression counter is reversed! That is, if there are 5 characters on Line 1, then whereas initially the caret starts from Position 0 on the right-hand side and increases as more text is added from right to left, it is now reversed where the the caret now increases from left to right for the first line, but correctly increases from right to left in the second line! yes funny stuff and very hard to describe to.
    So, here is an example. I wrote the code below (JDK1.6_u10, on Netbeans 6.5 RC2) to make it easy to reproduce the problem. In the example, I have replaced the keys A, S, D, F and G with their Arabic corresponding letters alif, seen, daal, faa and jeem. Now, type these letters inside the double quotes (without the double quotes) including the two spaces please and watch out for the output: "asdfg asdfg ". Up until you type the last g and before you type space, all is perfect, and you should notice that the caret position correctly moves from 0 upwards in the printlines I provided. When you type that last space, the second word descends as a result of the wrap-around, and hell breaks loose! Notice that whereas the mouse and caret position are coincident on the second line, there is no way to fine-control the mouse position on the first line any more. Further, whereas adding text on the second line is intuitive (i.e., you can insert more text wherever you point your mouse, which is also where the caret would show up), for the first line, if you point the mouse any place over the written string, the caret displays in a different place, the any added text is added in the wrong place! All this because the caret counter is now reversed, which should never occur. Any ideas or fixes?
    Thank you very much for reading.
    Mohsen
    package workshop.onframes;
    import java.awt.ComponentOrientation;
    import java.awt.Rectangle;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    public class NewJFrame1 extends javax.swing.JFrame {
    public NewJFrame1() {
    initComponents();
    jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
    CaretListener caretListener = new CaretListener() {
    public void caretUpdate(CaretEvent e) {
    int dot = e.getDot();
    int mark = e.getMark();
    if (dot == mark) {
    try {
    Rectangle cc = jTextPane1.modelToView(dot);
    System.out.println("Caret text position: " + dot +
    ", view location (x, y): (" + cc.x + ", " + cc.y + ")");
    } catch (BadLocationException ble) {
    System.err.println("CTP: " + dot);
    } else if (dot < mark) {
    System.out.println("Selection from " + dot + " to " + mark);
    } else {
    System.out.println("Selection from " + mark + " to " + dot);
    jTextPane1.addCaretListener(caretListener);
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
    jScrollPane3 = new javax.swing.JScrollPane();
    jTextPane1 = new javax.swing.JTextPane();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextPane1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
    jTextPane1.setAutoscrolls(false);
    jTextPane1.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyTyped(java.awt.event.KeyEvent evt) {
    jTextPane1KeyTyped(evt);
    jScrollPane3.setViewportView(jTextPane1);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE)
    .addContainerGap())
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    private void jTextPane1KeyTyped(java.awt.event.KeyEvent evt) {
    if (evt.getKeyChar() == 'a') {
    evt.setKeyChar('\u0627');
    } else if (evt.getKeyChar() == 's') {
    evt.setKeyChar('\u0633');
    } else if (evt.getKeyChar() == 'd') {
    evt.setKeyChar('\u062f');
    } else if (evt.getKeyChar() == 'f') {
    evt.setKeyChar('\u0641');
    } else if (evt.getKeyChar() == 'g') {
    evt.setKeyChar('\u062c');
    public
    static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new NewJFrame1().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextPane jTextPane1;
    // End of variables declaration
    }

    Hi Mohsen,
    I looked at it and indeed, I see what you describe. Sorry, but I can't shed any light. I tried to figure out what software component, or combination of components, is the cause of the problem. I see several candidates:
    1) The JTextPane
    2) The Document
    3) RTL support
    4) BIDI support
    5) Interpretation (by any other software component) of the left and right arrow key
    6) The font
    To clarify number 6: I know virtually nothing of Arabic language (apart from it being written from right to left). I remember however that the actual representation of a letter is dependent of its position between other letters: front, middle and end. What I see to my astonishment is that it seems that the rendering is also aware of this phenomenon. When you insert an A between the S and D of ASDFG, the shape of the S changes. Quite magic.
    I tried to add a second textpane with the same Document, but a different size, to see what would happen with number one if one types text in number two and vice versa.
    In my first attempt, the font that you set on textpane one was gone after I set its document to number two. For me that is very strange. The font was set to the textpane, not to the document. The separation betweem Model and View seems not very clear in this case. So I now also set that font on the second textpane.
    I will post the changed code so that you may experiment some more and hopefully will find the problem.
    You might be interested in a thread on java dot net forums that discusses a memory leak for RTL [http://forums.java.net/jive/message.jspa?messageID=300344#300344]
    Piet
    import java.awt.ComponentOrientation;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.Rectangle;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.GroupLayout;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    import javax.swing.event.CaretEvent;
    import javax.swing.event.CaretListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    public class NewJFrame1 extends JFrame {
        private static final long serialVersionUID = 1L;
        public NewJFrame1() {
         initComponents();
         // jTextPane1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         this.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         CaretListener caretListener = new CaretListener() {
             public void caretUpdate(CaretEvent e) {
              int dot = e.getDot();
              int mark = e.getMark();
              if (dot == mark) {
                  try {
                   Rectangle cc = jTextPane1.modelToView(dot);
                   System.out.println("Caret text position: " + dot
                        + ", view location (x, y): (" + cc.x + ", "
                        + cc.y + ")");
                  } catch (BadLocationException ble) {
                   System.err.println("CTP: " + dot);
              } else if (dot < mark) {
                  System.out.println("Selection from " + dot + " to " + mark);
              } else {
                  System.out.println("Selection from " + mark + " to " + dot);
         jTextPane1.addCaretListener(caretListener);
        private KeyAdapter toArabic = new KeyAdapter() {
         public void keyTyped(KeyEvent evt) {
             jTextPane1KeyTyped(evt);
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
        // @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
         jScrollPane3 = new JScrollPane();
         jTextPane1 = new JTextPane();
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         jTextPane1.setFont(new Font("Tahoma", 0, 24)); // NOI18N
         jTextPane1.setAutoscrolls(false);
         jTextPane1.addKeyListener(toArabic);
         jScrollPane3.setViewportView(jTextPane1);
         GroupLayout layout = new GroupLayout(getContentPane());
         getContentPane().setLayout(layout);
         layout.setHorizontalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.DEFAULT_SIZE, 159,
                   Short.MAX_VALUE).addContainerGap()));
         layout.setVerticalGroup(layout.createParallelGroup(
              GroupLayout.Alignment.LEADING).addGroup(
              layout.createSequentialGroup().addContainerGap().addComponent(
                   jScrollPane3, GroupLayout.PREFERRED_SIZE, 85,
                   GroupLayout.PREFERRED_SIZE).addContainerGap(
                   GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
         pack();
        }// </editor-fold>
        private void jTextPane1KeyTyped(KeyEvent evt) {
         if (evt.getKeyChar() == 'a') {
             evt.setKeyChar('\u0627');
         } else if (evt.getKeyChar() == 's') {
             evt.setKeyChar('\u0633');
         } else if (evt.getKeyChar() == 'd') {
             evt.setKeyChar('\u062f');
         } else if (evt.getKeyChar() == 'f') {
             evt.setKeyChar('\u0641');
         } else if (evt.getKeyChar() == 'g') {
             evt.setKeyChar('\u062c');
        public static void main(String args[]) {
         EventQueue.invokeLater(new Runnable() {
             public void run() {
              final NewJFrame1 frameOne = new NewJFrame1();
              frameOne.setLocationRelativeTo(null);
              frameOne.setVisible(true);
              EventQueue.invokeLater(new Runnable() {
                  public void run() {
                   Document doc = frameOne.jTextPane1.getDocument();
                   JTextPane textPane2 = new JTextPane();
                   textPane2.setFont(new Font("Tahoma", 0, 24)); // NOI18N
                   textPane2.setAutoscrolls(false);
                   textPane2.setDocument(doc);
                   textPane2.addKeyListener(frameOne.toArabic);
                   JFrame frameTwo = new JFrame();
                   frameTwo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   frameTwo.add(new JScrollPane(textPane2));
                   frameTwo.setSize(400, 300);
                   frameTwo.setLocationByPlatform(true);
                   frameTwo.setVisible(true);
                   frameTwo
                        .applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        // Variables declaration - do not modify
        private JScrollPane jScrollPane3;
        private JTextPane jTextPane1;
        // End of variables declaration
    }

  • Out of Memory error in  JTextPane

    Hi all,
    A application contains four JTextPanes.The features supported are foreground,background colouring,editing etc...
    When i try to load a file
    containing 10,000 lines i get "out of memory error".
    What is the maximum number of characters or lines that can be
    represented in a JTextPane.
    I find a lot of objects related to JTextPane getting created.
    Is there any work around to avoid this?.
    Has any one faced this problem already?.
    The forum already contains the question but no replies to it.
    Thanks.

    Has any one faced this problem already?.assuming you're having the same problem (sure sounds similar)...
    see my thread here:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=340872
    there's a bug in jtextarea, jtextpane and jeditorpane. a link to the initial bug report (jtextarea) is in there. i duplicated the bug in all three components by creating a blank jframe with the component in question on it. memory use skyrocketed with all three
    i already cast two votes for for the bug to be fixed. i don't know how sun can expect people to adopt java when there are debilitating problems such as these...
    anyway, try using an awt text area instead...that is, if you don't need to make use of the extra features of jtextpane. using the awt text area solved my problems.

  • JTextPane not editable in JWindow???

    Hi everyone,
    My problem is this, I have another JFrame that will call this Sticky class which creates a JWindow but I can't edit the JTextPane noteText. I tried setEditable, setEnabled, requestFocus, etc but I just can't edit it. It does work if I use a JFrame instead of a JWindow but I don't want to use the window bar thingy. Any suggestions? Much thanks!
    Felix
    public class Sticky extends JWindow implements ActionListener, MouseMotionListener {
        JPanel notePane;
        public Sticky (String message) {
            super();
            notePane = new JPanel();
            notePane.addMouseMotionListener(this);
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.Y_AXIS));
            JButton closeButton = Kronos.createButton("X", "Close this sticky", this);
            buttonPane.add(closeButton);
            JButton colorButton = Kronos.createButton("C", "Choose the color", this);
            buttonPane.add(colorButton);
            notePane.add(buttonPane);
            JTextPane noteText = new JTextPane();
            noteText.setText(message);
            JScrollPane noteScroll = new JScrollPane(noteText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
            noteScroll.setPreferredSize(new Dimension(200,100));
            notePane.add(noteScroll);
            this.getContentPane().add(notePane);
            this.setLocationRelativeTo(null);
            this.pack();
            this.setVisible(true);
    }

    Thanks for the link but unfortunately, that's not what I am looking for. With this code,
            super(parentFrame);
            this.setFocusableWindowState(true);
            this.setFocusable(true);whenever I minimize the parent frame, the jwindow also minimizes.
    Is there another way, or is this, like they said, a bug?

Maybe you are looking for

  • Deactivation . Crash hard drive. New computer. Photoshop CS6 and Lightroom 5.7

    I have both desktop and laptop. Photoshop cs6 and Lightroom 5.7 installed on both. My desktop hard drive crashed and I can't deactivate both Photoshop cs6 and Lightroom 5.7 on the desktop. I believe I have 2 activations on both Photoshop and Lightroo

  • Bug - Import Excel File into Indesign cs5.5

    Hi, I'm doing a complex Indesign file with a link to a Excel file. To import the Excel file I have created several tables always using styles (table, cell, paragraph). The problem born when I make a correction into the file Excel and I update the lin

  • Smart View deleting formulas on refresh

    Hi everyone, We're using SV 11.1.1.3.00 to pull info into excel 2003, and I'm trying to understand the do's and dont's when refreshing the data. At this point, I'm not sure if that's just the way it is, or something else - On an initial refresh with

  • Calling a User defined function from Data Model in BIP

    I am new to Procedures and Functions and am not sure if I am doing it right, so please bear with me. My User Function: create function MyTempFunction(@master_key varchar(max)) returns VARCHAR(MAX) begin DECLARE @Names VARCHAR(8000) SELECT @Names = CO

  • Control + Click and Drag

    Hi there, Scenario I need to use Google Chrome on my early 2011, 13' Macbook Pro (running Mavericks 10.9.2) for an online job. They have their own interface which is only supported by Chrome and not Safari or any other browsers. Problem On some speci