JTextPane lineWrap at 4096. Changeable?

JTextPane seems to be wrapping a single line after 4096 characters. I tried to look at the JTextPane/JEditorPane classes source code but cant find anything that defines that. Anyone knows where it is defined so I can set it higher? thanks.

Because I want to color text. I can highlight with JTextArea but just one character, not multiple. I can also use html headers but that complicates my algorithm.

Similar Messages

  • How to gettext from textarea in a new line when the linewrap option is true

    Hello everyone..
    I wanted to know that how get we get text from the Jtextarea when the linewrap option is set to true..
    for example..
    Lets say my textarea can have 50 chars without any kind of wrap..
    now when the 51 st char is pressed or entered it automatically goes to the next line..
    now i want to get the text from the textarea and display it in the exact fashion as it is in the textarea..
    Please help me out in this case..

    This can help, if not, take a JTextPane. In my program,
    I get all lines (including wrapped ones) with that
    I hope, there are no indexing or so errors, I had to adapt my code
    a bit.
    View root =
    myJTextComponent.getUI().getRootView(myJTextComponent).getView(0);
    int number_of_paragraphs = root.getViewCount();
    int linestart, lineend;
    String line;
    for(int paragraphindex = 0; paragraphindex< number_of_paragraphs;
    paragraphindex++)
         for(int line_in_paragaph = 0; line_in_paragraph <          
         root.getView(paragraphindex).getViewCount(); line_in_paragraph++)
         linestart =   root.getView(paragraphindex).getView(line_in_paragraph).getStartOffset();
         lineend=
         root.getView(paragraphindex).getView(line_in_paragraph).getEndOffset();
            try
            line = myJTextComponent.getDocument().getText(linestart,
            lineend-linestart);
            System.out.println(line);
            catch(BadLocationException e) {...}
    }

  • ComponentView does not redraw component in JTextPane Cell Rend

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

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

  • Problem with JTextPane and StateInvariantError

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

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

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

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

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

  • PO Changeability / Release Strategy / BAPI_PO_RELEASE Issue

    Hello everyone,
    I've run into an interesting problem:
    We have defined several PO release strategies.  Most of these work in the traditional manner, requiring manual approval by a given user.  One release strategy, "99," gets picked up by a batch job and released automatically using BAPI_PO_RELEASE. Either way, the release indicator for all released PO's is set to "R." This all works as intended.
    We have maintained Changeability settings for each release indicator in customizing. "R" is set to "4 - Changeable, new release in case of new strat. or val. change," with a percent value change tolerance of 10%.
    If we make a change to a manually released PO that exceeds the threshold set in customizing, the release procedure starts over as intended.
    If we make a change exceeding the threshold to a PO that was released automatically by BAPI_PO_RELEASE, the release procedure does not start over, and the PO remains unblocked.
    What would cause this discrepancy?  The two records look virtually identical in EKKO, particularly in respect to the fields relevant to release.
    Thank you ahead of time for your help.
    -Jarrod

    Configuration issue/user error.

  • Multi-document Application using JTextPane - Issue

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

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

  • 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

  • How to get exact height of HTML line with SUB tag in JTextPane?

    Hi, this is my first post. I`ve been searching forum for an answer for a week, but didn`t find one.
    I have HTMLDocument inside JTextPane(exacty inside my class that extends it - MyTextPane). I want to do some custom painting in JTextPane so I need to be able to know exact pixel witdh for each line in the document. Easy except one thing, when I use SUB tag the width of the line cannot be simply calculated using FontMetrics, because I don`t know if the text inside SUB tag has lower font size and I don`t know its Y offset to normal line.
    I tried get these information from HTMLDocument using attributes from leafElements representing lines, but there seems to be a problem too.
    I pass this text:
    "(1) Line<SUB>jW</SUB><BR>(2) TextB"
    to setText method of MyTextPane, this method is overriden so it changes text Font
    public void setText(String s) {   
      super.setText(s);   
      setJTextPaneFont(this, new Font("Arial",Font.PLAIN,36), Color.black);
    }This is how the Element Structure looks like:
    Format is Element +": "+elementText+"|"+fontFamily+" "+fontSize
    BranchElement(html) 0,22: \n(1)?LinejW (2)?TextB\n|Monospaced 12
    ---BranchElement(head) 0,1: \n|Monospaced 12
    ------BranchElement(p-implied) 0,1: \n|Monospaced 12
    ---------LeafElement(content) 0,1: \n|Arial 36
    ---BranchElement(body) 1,22: (1) LinejW (2) TextB\n|Monospaced 12
    ------BranchElement(p-implied) 1,22: (1) LinejW (2) TextB\n|Monospaced 12
    ---------LeafElement(content) 1,9: (1) Line|Arial 36
    ---------LeafElement(content) 9,11: jW|Arial 36 <-----------THIS IS THE LOWER INDEX
    ---------LeafElement(content) 11,12: |Arial 36 <-----------THIS IS just space character '\u020'
    ---------LeafElement(content) 12,21: (2) TextB|Arial 36
    ---------LeafElement(content) 21,22: \n|Arial 36
    The height of Arial 36 is according to FontMetrics 43(and it really is), but height of the lowerIndex is just 40 pixels(on the screen), not 43 as I would expect. And I still dont have offset, where does the lower index starts paint itself.
    Is there any problem with my setText method, so that it changes font style for LOWER INDEX?
    I am using JTextPane as notEditable, with just one font style for entire document.
    Any suggestion?

    Is there any other way to get these information. I just found that I need that information before I put text it in the document.
    For example I am would like to generate lines:
    paragraph1 - text1
                             text2
    paragraph2 - text1
                             text2
                             text3
    paragraph3<SUB>some note</SUB> - text1
                                                                           text2
    normal text line
    I know what font line will be and I know its AttributeSet. I am trying to get appropriate number of spaces (or left indent) for text2,text3...lines. Then I will pass that string to setText method of JTextPane.
    I am unable to get appropriate width for "paragraph3<SUB>some note</SUB> - ", since text in SUB tag uses probably different font size.
    I am really sorry to bother again. I will think twice what I need before I posting.
    You`ve been very helpful so far Stas.
    Thanks.

  • Display image in JTextPane (JEditorPane)

    I'm writing an application with JTable and a JTextPane. When selecting a column in the JTable, I want to display the image associated with the selected row in the JTextPane.
    This wouldn't be a problem if the darn JTextPane would just display JUST AN IMAGE. But a JTextPane only displays an image if its embedded in an HTML file. Ugh. That would mean I'd have to create an html file for each picture. Ugh again.
    Is there any way around this?

    Nevermind, figured it out. Just have to use setText instead of setPage.
    htmlPane.setText("<IMG src='"+url+"'>");instead of:
    htmlPane.setPage(url);

  • Line Number in JTextPane

    Hi Experts;
    How do I add a caret listener on this code so that it will just add a number
    when the user goes to the next line.
    import java.awt.*;
    import javax.swing.*;
    public class LineNumber extends JComponent
         private final static Color DEFAULT_BACKGROUND = new Color(213, 213, 234);
         private final static Color DEFAULT_FOREGROUND = Color.white;
         private final static Font DEFAULT_FONT = new Font("arial", Font.PLAIN, 11);
         // LineNumber height (abends when I use MAX_VALUE)
         private final static int HEIGHT = Integer.MAX_VALUE - 1000000;
         // Set right/left margin
         private final static int MARGIN = 5;
         // Line height of this LineNumber component
         private int lineHeight;
         // Line height of this LineNumber component
         private int fontLineHeight;
         // With of the LineNumber component
         private int currentRowWidth;
         // Metrics of this LineNumber component
         private FontMetrics fontMetrics;
          * Convenience constructor for Text Components
         public LineNumber(JComponent component)
              if (component == null)
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( DEFAULT_FOREGROUND );
                   setFont( DEFAULT_FONT );
              else
                   setBackground( DEFAULT_BACKGROUND );
                   setForeground( DEFAULT_FOREGROUND );
                   setFont( component.getFont() );
              setPreferredSize( 99 );
         public void setPreferredSize(int row)
              int width = fontMetrics.stringWidth( String.valueOf(row) );
              if (currentRowWidth < width)
                   currentRowWidth = width;
                   setPreferredSize( new Dimension(2 * MARGIN + width, HEIGHT) );
         public void setFont(Font font)
              super.setFont(font);
              fontMetrics = getFontMetrics( getFont() );
              fontLineHeight = fontMetrics.getHeight();
          * The line height defaults to the line height of the font for this
          * component. The line height can be overridden by setting it to a
          * positive non-zero value.
         public int getLineHeight()
              if (lineHeight == 0)
                   return fontLineHeight;
              else
                   return lineHeight;
         public void setLineHeight(int lineHeight)
              if (lineHeight > 0)
                   this.lineHeight = lineHeight;
         public int getStartOffset()
              return 4;
         public void paintComponent(Graphics g)
               int lineHeight = getLineHeight();
               int startOffset = getStartOffset();
               Rectangle drawHere = g.getClipBounds();
               g.setColor( getBackground() );
               g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height);
               g.setColor( getForeground() );
               int startLineNumber = (drawHere.y / lineHeight) + 1;
               int endLineNumber = startLineNumber + (drawHere.height / lineHeight);
               int start = (drawHere.y / lineHeight) * lineHeight + lineHeight - startOffset;
               for (int i = startLineNumber; i <= endLineNumber; i++)
               String lineNumber = String.valueOf(i);
               int width = fontMetrics.stringWidth( lineNumber );
               g.drawString(lineNumber, MARGIN + currentRowWidth - width, start);
               start += lineHeight;
               setPreferredSize( endLineNumber );
    } Thanks for your time . . .
    The_Developer

    Here's what I use. It behaves correctly WRT wrapped lines, and should work equally well with a JTextArea or a JTextPane.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.BorderFactory;
    import javax.swing.JComponent;
    import javax.swing.SizeSequence;
    import javax.swing.UIManager;
    import javax.swing.event.DocumentEvent;
    import javax.swing.event.DocumentListener;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Document;
    import javax.swing.text.Element;
    import javax.swing.text.JTextComponent;
    * LineNumberView is a simple line-number gutter that works correctly
    * even when lines are wrapped in the associated text component.  This
    * is meant to be used as the RowHeaderView in a JScrollPane that
    * contains the associated text component.  Example usage:
    *<pre>
    *   JTextArea ta = new JTextArea();
    *   ta.setLineWrap(true);
    *   ta.setWrapStyleWord(true);
    *   JScrollPane sp = new JScrollPane(ta);
    *   sp.setRowHeaderView(new LineNumberView(ta));
    *</pre>
    * @author Alan Moore
    public class LineNumberView extends JComponent
      // This is for the border to the right of the line numbers.
      // There's probably a UIDefaults value that could be used for this.
      private static final Color BORDER_COLOR = Color.GRAY;
      private static final int WIDTH_TEMPLATE = 99999;
      private static final int MARGIN = 5;
      private FontMetrics viewFontMetrics;
      private int maxNumberWidth;
      private int componentWidth;
      private int textTopInset;
      private int textFontAscent;
      private int textFontHeight;
      private JTextComponent text;
      private SizeSequence sizes;
      private int startLine = 0;
      private boolean structureChanged = true;
       * Construct a LineNumberView and attach it to the given text component.
       * The LineNumberView will listen for certain kinds of events from the
       * text component and update itself accordingly.
       * @param startLine the line that changed, if there's only one
       * @param structureChanged if <tt>true</tt>, ignore the line number and
       *     update all the line heights.
      public LineNumberView(JTextComponent text)
        if (text == null)
          throw new IllegalArgumentException("Text component cannot be null");
        this.text = text;
        updateCachedMetrics();
        UpdateHandler handler = new UpdateHandler();
        text.getDocument().addDocumentListener(handler);
        text.addPropertyChangeListener(handler);
        text.addComponentListener(handler);
        setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, BORDER_COLOR));
       * Schedule a repaint because one or more line heights may have changed.
       * @param startLine the line that changed, if there's only one
       * @param structureChanged if <tt>true</tt>, ignore the line number and
       *     update all the line heights.
      private void viewChanged(int startLine, boolean structureChanged)
        this.startLine = startLine;
        this.structureChanged = structureChanged;
        revalidate();
        repaint();
      /** Update the line heights as needed. */
      private void updateSizes()
        if (startLine < 0)
          return;
        if (structureChanged)
          int count = getAdjustedLineCount();
          sizes = new SizeSequence(count);
          for (int i = 0; i < count; i++)
            sizes.setSize(i, getLineHeight(i));
          structureChanged = false;
        else
          sizes.setSize(startLine, getLineHeight(startLine));
        startLine = -1;
      /* Copied from javax.swing.text.PlainDocument */
      private int getAdjustedLineCount()
        // There is an implicit break being modeled at the end of the
        // document to deal with boundary conditions at the end.  This
        // is not desired in the line count, so we detect it and remove
        // its effect if throwing off the count.
        Element map = text.getDocument().getDefaultRootElement();
        int n = map.getElementCount();
        Element lastLine = map.getElement(n - 1);
        if ((lastLine.getEndOffset() - lastLine.getStartOffset()) > 1)
          return n;
        return n - 1;
       * Get the height of a line from the JTextComponent.
       * @param index the line number
       * @param the height, in pixels
      private int getLineHeight(int index)
        int lastPos = sizes.getPosition(index) + textTopInset;
        int height = textFontHeight;
        try
          Element map = text.getDocument().getDefaultRootElement();
          int lastChar = map.getElement(index).getEndOffset() - 1;
          Rectangle r = text.modelToView(lastChar);
          height = (r.y - lastPos) + r.height;
        catch (BadLocationException ex)
          ex.printStackTrace();
        return height;
       * Cache some values that are used a lot in painting or size
       * calculations. Also ensures that the line-number font is not
       * larger than the text component's font (by point-size, anyway).
      private void updateCachedMetrics()
        Font textFont = text.getFont();
        FontMetrics fm = getFontMetrics(textFont);
        textFontHeight = fm.getHeight();
        textFontAscent = fm.getAscent();
        textTopInset = text.getInsets().top;
        Font viewFont = getFont();
        boolean changed = false;
        if (viewFont == null)
          viewFont = UIManager.getFont("Label.font");
          changed = true;
        if (viewFont.getSize() > textFont.getSize())
          viewFont = viewFont.deriveFont(textFont.getSize2D());
          changed = true;
        viewFontMetrics = getFontMetrics(viewFont);
        maxNumberWidth = viewFontMetrics.stringWidth(String.valueOf(WIDTH_TEMPLATE));
        componentWidth = 2 * MARGIN + maxNumberWidth;
        if (changed)
          super.setFont(viewFont);
      public Dimension getPreferredSize()
        return new Dimension(componentWidth, text.getHeight());
      public void setFont(Font font)
        super.setFont(font);
        updateCachedMetrics();
      public void paintComponent(Graphics g)
        updateSizes();
        Rectangle clip = g.getClipBounds();
        g.setColor(getBackground());
        g.fillRect(clip.x, clip.y, clip.width, clip.height);
        g.setColor(getForeground());
        int base = clip.y - textTopInset;
        int first = sizes.getIndex(base);
        int last = sizes.getIndex(base + clip.height);
        String text = "";
        for (int i = first; i <= last; i++)
          text = String.valueOf(i+1);
          int x = MARGIN + maxNumberWidth - viewFontMetrics.stringWidth(text);
          int y = sizes.getPosition(i) + textFontAscent + textTopInset;
          g.drawString(text, x, y);
      class UpdateHandler extends ComponentAdapter
          implements PropertyChangeListener, DocumentListener
         * The text component was resized. 'Nuff said.
        public void componentResized(ComponentEvent evt)
          viewChanged(0, true);
         * A bound property was changed on the text component. Properties
         * like the font, border, and tab size affect the layout of the
         * whole document, so we invalidate all the line heights here.
        public void propertyChange(PropertyChangeEvent evt)
          Object oldValue = evt.getOldValue();
          Object newValue = evt.getNewValue();
          String propertyName = evt.getPropertyName();
          if ("document".equals(propertyName))
            if (oldValue != null && oldValue instanceof Document)
              ((Document)oldValue).removeDocumentListener(this);
            if (newValue != null && newValue instanceof Document)
              ((Document)newValue).addDocumentListener(this);
          updateCachedMetrics();
          viewChanged(0, true);
         * Text was inserted into the document.
        public void insertUpdate(DocumentEvent evt)
          update(evt);
         * Text was removed from the document.
        public void removeUpdate(DocumentEvent evt)
          update(evt);
         * Text attributes were changed.  In a source-code editor based on
         * StyledDocument, attribute changes should be applied automatically
         * in response to inserts and removals.  Since we're already
         * listening for those, this method should be redundant, but YMMV.
        public void changedUpdate(DocumentEvent evt)
    //      update(evt);
         * If the edit was confined to a single line, invalidate that
         * line's height.  Otherwise, invalidate them all.
        private void update(DocumentEvent evt)
          Element map = text.getDocument().getDefaultRootElement();
          int line = map.getElementIndex(evt.getOffset());
          DocumentEvent.ElementChange ec = evt.getChange(map);
          viewChanged(line, ec != null);
    }

  • 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

  • How Do I Make Text Colored in a JTextPane

    I currently have a program that uses a JTextArea to display text that the user has typed into a Text Field. This is working and i now want to be able to make parts of this text different colors. I was looking in the tutorials and it looks like i need to use a JTextPane but i am not sure how to do this, does anyone have any advice? Thanks in advance.

    going86 wrote:
    The tutorial does not explain hot to do it very well, it is hard to understand.Then give it your best shot, and come back with your code and your specific points of misunderstanding. The onus of effort here must be on you.

  • Linux Serial NI-VISA - Can the buffer size be changed from 4096?

    I am communicating with a serial device on Linux, using LV 7.0 and NI-VISA. About a year and a half ago I had asked customer support if it was possible to change the buffer size for serial communication. At that time I was using NI-VISA 3.0. In my program the VISA function for setting the buffer size would send back an error of 1073676424, and the buffer would always remain at 4096, no matter what value was input into the buffer size control. The answer to this problem was that the error code was just a warning, letting you know that you could not change the buffer size on a Linux machine, and 4096 bytes was the pre-set buffer size (unchangeable). According to the person who was helping me: "The reason that it doesn't work on those platforms (Linux, Solaris, Mac OSX) is that is it simply unavailable in the POSIX serial API that VISA uses on these operating systems."
    Now I have upgraded to NI-VISA 3.4 and I am asking the same question. I notice that an error code is no longer sent when I input different values for the buffer size. However, in my program, the bytes returned from the device max out at 4096, no matter what value I input into the buffer size control. So, has VISA changed, and it is now possible to change the buffer size, but I am setting it up wrong? Or, have the error codes changed, but it is still not possible to change the buffer size on a Linux machine with NI-VISA?
    Thanks,
    Sam

    The buffer size still can't be set, but it seems that we are no longer returning the warning. We'll see if we can get the warning back for the next version of VISA.
    Thanks,
    Josh

  • View the Text in JTextPane when we r inserting another text

    Hi,
    I have created GUI in swing where i have taken JTextPane.I am seaching some keyword which r given by the client if i found so i am creating the pdf file for that data and in JTextPane i am showing the pdf file name .....if i am getting that keyword in the database then i am showing some different color string that " keyword not found with that keyword" .........while this process takes too much time to create pdf....till that time JTextPane is not showing any text.........in this case i want that the text should show in the JTextPane once the single Pdf file get created and so on to create 100 PDF file...plase sugget me somthing ......thanx

    Hi,
    Thanks a lot for ur support..Now i am getting updated JTextPane..
    Can u provide me a link with the help of which i can use multiple threads
    1.to get information from the database.......to collect data from database.
    2.to search the keyword in that database.
    3.to print the search condition in the JTextPane
    4.Final is to create PDF.
    So i have to do above 4 steps out of which last step(4th) that is to create PDF is time consuming...So give me guidence with the help of which i can make maximum use of threads for faster execution.....thanx

Maybe you are looking for

  • Flex Builder Engineer needed

    Flex Builder Engineer need for profitable startup in the SF bay.  *No overseas relocations* Job Description: This would be a great opportunity for experienced IDE developer, such as Flex, who want to move to cutting-edge web and mobile technology in

  • Drop Down in ALV

    Hi, i have a problem to insert value in drop down list in ALV. (I want to use  this call function CALLFUNCTION 'REUSE_ALV_GRID_DISPLAY_LVC' or 'REUSE_ALV_GRID_DISPLAY) How can i  insert directly in ABAP 3 value. Example of code you can test this : re

  • Where is my serial number for convert to PDF

    I did not receive an e-mail or a cd.  I bought it on 11 Nov 14 for 89.99.  When I am in my e-mail trying to look at something someone sent me I get the pop up to buy it again or it wants a serial number which I don't have.  If I go to it from my desk

  • Why won't flash video's work on my iBook anymore?

    so, previously i didn't have a problem watching flash video on my iBook. whne i say previoulsy i mean that serveral month ago i change the OS to 5.8. how i have problem's somehow relating to the flash players on sites. i don't think it effects YouTub

  • MAP price in FG

    Dear consultants. The scenario is like this- The materials are transfered from different plants of different location having different std price, to assembly plants for further process. Currently these materials are maintained as FG with STD price.Fo