JTextPane

How can I disable the word wrap in a JTextPane?

hmm i don't know if thats possible...
i was looking on the web actually and i ran across this:
http://skunkdav.sourceforge.net/doc/org/skunk/swing/text/TextEditorPane.html
i think someone recognized this problem and created a new package which you can download, which will do this.
other than that i can't think of anything.....i read somewhere that you can only do it by changing the JScrollPane the JTextPane is inside of, like minimizing the vertical scrollpane.
--good luck!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • 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

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

  • 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

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • How to get the text in a label which is imbeded in a JTextPane

    I have created a JTextPane that has 5 JLabels inserted in the text. I have attempted to get the text with the following code snippet.
    Component[] lbl = new Componennt[DisplayLetterPane.getComponentCount()];
    //         JTextPane DisplayLetterPane; is defined previously
             lbl = DisplayLetterPane.getComponents();
             int componentIndex = 0;
             String lblText = new String(((JLabel)lbl[componentIndex]).getText());I have run a dump of the sytledDocument of the JTextPane and I see the JLabel listed as a component.
    When this snippet is executed I get the following:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.text.ComponentView$Invalidator
    When I check the character where the component for the JLabel is located in the styled document it does not find an instanceof JLabel.
    How can I get the text from the labels.
    Thank you in advance!

    JTextPane jtp = new JTextPane();
              for (int i = 0; i <5; i++) {
                   jtp.add(new JLabel("labelText"+i));
              Component[] lbl = new Component[jtp.getComponentCount()];
    //      JTextPane DisplayLetterPane; is defined previously
          lbl = jtp.getComponents();
          int componentIndex = 0;
          for (int i = 0; i < lbl.length; i++) {
               System.out.println(((JLabel)lbl).getText());
    When I do like the above, it just works fine. Can u share a little bit more of your code?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Exception while adding a chrtpanel(component of JFreeChart) to JTextPane.

    hi,
    Please help for solving the following exception while adding a chrtpanel(component of JFreeChart) to JTextPane
    java.lang.ArrayIndexOutOfBoundsException: No such child: 0
         at java.awt.Container.getComponent(Container.java:237)
         at javax.swing.text.ComponentView$Invalidator.cacheChildSizes(ComponentView.jav
    a:399)
         at javax.swing.text.ComponentView$Invalidator.doLayout(ComponentView.java:383)
         at java.awt.Container.validateTree(Container.java:1092)
         at java.awt.Container.validate(Container.java:1067)
         at javax.swing.text.ComponentView$Invalidator.validateIfNecessary(ComponentView
    .java:394)
         at javax.swing.text.ComponentView$Invalidator.getPreferredSize(ComponentView.ja
    va:427)
         at javax.swing.text.ComponentView.getPreferredSpan(ComponentView.java:119)
         at javax.swing.text.FlowView$LogicalView.getPreferredSpan(FlowView.java:679)
         at javax.swing.text.FlowView.calculateMinorAxisRequirements(FlowView.java:214)
         at javax.swing.text.BoxView.checkRequests(BoxView.java:913)
         at javax.swing.text.BoxView.getMinimumSpan(BoxView.java:542)
         at javax.swing.text.BoxView.calculateMinorAxisRequirements(BoxView.java:881)
         at javax.swing.text.BoxView.checkRequests(BoxView.java:913)
         at javax.swing.text.BoxView.setSpanOnAxis(BoxView.java:325)
         at javax.swing.text.BoxView.layout(BoxView.java:682)
         at javax.swing.text.BoxView.setSize(BoxView.java:379)
         at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1599)
         at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:801)
         at javax.swing.JComponent.getPreferredSize(JComponent.java:1275)
         at javax.swing.JEditorPane.getPreferredSize(JEditorPane.java:1212)
         at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:769)
         at java.awt.Container.layout(Container.java:1020)
         at java.awt.Container.doLayout(Container.java:1010)
         at java.awt.Container.validateTree(Container.java:1092)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validateTree(Container.java:1099)
         at java.awt.Container.validate(Container.java:1067)
         at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:353
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQu
    eueUtilities.java:116)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:454)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.ja
    va:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java
    :151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

    I tried with the following link
    http://www.onjava.com/pub/a/onjava/2004/03/10/blackmamba.html?page=2
    one place this one is getting solved. Some other places atill the exeception is present.

  • Multi-line JTextPane: My SSCCE works, but not my reg. code . [LONG, sorry.]

    So, I'm trying to code this flash cards program, and it's not working. The problem is that, when I change the text of the JTextPane to have multiple lines, the text disappears, and my JTextPane acts like it's empty. I included my SSCCE as a comparison, because it works just fine. I hope you guys don't mind that I included all of the code for my Cards program, even the stuff that I know isn't relevant, but I'm at a loss, and it's bedtime, so I'm done editing for the night. If you guys can fix my code, feel free to use it for your own personal use (as a reward for having to deal with the irrelevant stuff). How do I get my text to appear when it has multiple lines?
    PS I know my button listeners aren't like they should be. I'm going to fix them after I fix the JTextPane.
    PPS If this breaks anyone's browser, I'm sorry, but I included a file that is format-dependent, so I had to include it as is. Also, I had to include tabs and not spaces because of the length limit.
    package sscce;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    public class SSCCE
         private final Font     bold          = new Font("Courier New", Font.BOLD, 12),
              plain = new Font("Courier New", Font.PLAIN, 12);
         JButton                    button          = new JButton("Press this button");
         final JLabel          labels[]     = {new JLabel("xyz"), new JLabel("xyz"),
              new JLabel("xyz"), new JLabel("xyz"), new JLabel("xyz"),
              new JLabel("xyz")               };
         final String          oldText          = "This text should wrap automatically because it is long.",
              newText = "This text should add height to the textPane because it is longer than the original.";
         boolean                    textSwitch     = true;
         final JTextPane          tp               = createTextPane();
         final JPanel          upperPanel     = new JPanel(new GridLayout(3, 1)),
              lowerPanel = new JPanel(new GridBagLayout());
         private SSCCE()
              final JFrame frame = new JFrame("SSCCE");
              button.addActionListener(new ButtonListener());
              start();
              frame.add(upperPanel, BorderLayout.CENTER);
              frame.add(lowerPanel, BorderLayout.SOUTH);
              frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
              frame.setSize(485, 338);
              frame.setVisible(true);
         public static void main(final String args[])
              new SSCCE();
         private void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan)
              addItem(cell, colSpan, rowSpan, pan, new JLabel(" "), plain);
         private void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c, final Font f)
              final GridBagConstraints gc =
                   new GridBagConstraints(cell.charAt(0) - 65, cell.charAt(1) - 49,
                        colSpan, rowSpan, 100, 100, GridBagConstraints.CENTER,
                        GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
              try
                   pan.setFont(f);
                   pan.add(c, gc);
                   pan.validate();
              catch (final Exception e)
                   e.printStackTrace();
                   System.exit(0);
         private JTextPane createTextPane()
              final StyleContext context = new StyleContext();
              final StyledDocument document = new DefaultStyledDocument(context);
              final Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
              final JTextPane textPane = new JTextPane(document);
              textPane.setText(oldText);
              StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER);
              textPane.setFont(new Font("Courier New", Font.BOLD, 12));
              textPane.setEditable(false);
              return textPane;
         private void start()
              upperPanel.setBackground(Color.WHITE);
              upperPanel.setLayout(new GridLayout(3, 1));
              lowerPanel.setLayout(new GridBagLayout());
              final JPanel topPanel = new JPanel(new GridBagLayout()), middlePanel =
                   new JPanel(new GridBagLayout()), bottomPanel =
                   new JPanel(new GridBagLayout());
              topPanel.setBackground(Color.RED);
              middlePanel.setBackground(Color.GREEN);
              bottomPanel.setBackground(Color.BLUE);
              upperPanel.setBackground(Color.BLACK);
              addItem("A1", 1, 1, topPanel);
              addItem("A2", 1, 1, topPanel, new JLabel("test1"), plain);
              addItem("A3", 1, 1, topPanel);
              addItem("A1", 1, 1, middlePanel);
              addItem("A2", 1, 1, middlePanel, tp, bold);
              addItem("A3", 1, 1, middlePanel);
              addItem("A1", 1, 1, bottomPanel);
              addItem("A2", 1, 1, bottomPanel, new JLabel("test2"), plain);
              addItem("A3", 1, 1, bottomPanel);
              addItem("A1", 1, 1, lowerPanel);
              addItem("B1", 1, 1, lowerPanel, button, plain);
              addItem("C1", 1, 1, lowerPanel);
              upperPanel.add(topPanel);
              upperPanel.add(middlePanel);
              upperPanel.add(bottomPanel);
         private class ButtonListener implements ActionListener
              @Override
              public void actionPerformed(final ActionEvent arg0)
                   if (textSwitch)
                        tp.setText(newText);
                   else
                        tp.setText(oldText);
                   textSwitch = !textSwitch;
    package fc;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.GridLayout;
    import java.awt.Insets;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.util.Arrays;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.JTextPane;
    import javax.swing.WindowConstants;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.Style;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.StyledDocument;
    public class Cards implements ActionListener, FocusListener
         private Cards          allDefs[]          = null;
         private final Font     bold               = new Font("Courier New", Font.BOLD, 12),
              plain = new Font("Courier New", Font.PLAIN, 12);
         private JButton          button1               = null;
         private JButton          button2               = null;
         private final int     card               = 0;
         private final int     CE                    = GridBagConstraints.CENTER,
              E = GridBagConstraints.EAST, W = GridBagConstraints.WEST;
         private boolean          clickedWrong     = true;
         private String          course               = null, def = null, page = null,
              word = null;
         private JLabel          courseLabel          = null;
         private Cards          currDef               = null;
         private JTextArea     enterDefn          = null, enterWord = null;
         private JFrame          frame               = null;
         private JButton          invis               = null;
         private JButton          learn               = null;
         private boolean          message               = true;
         private JPanel          p[]                    = null;
         private JLabel          pageLabel          = null;
         private JPanel          panel[]               = null;
         private JTextArea     rightDefn          = null;
         private JTextArea     rightWord          = null;
         private Cards          saveDefs[]          = null;
         private JTextPane     showLabel          = null;
         private JLabel          sizeLabel          = null;
         public Cards()
              try
                   panel = new JPanel[2];
                   panel[0] = new JPanel();
                   panel[1] = new JPanel();
                   panel[0].removeAll();
                   panel[1].removeAll();
                   panel[0].revalidate();
                   panel[1].revalidate();
                   allDefs = populate();
                   button1 = new JButton();
                   button2 = new JButton();
                   learn = new JButton("Learn");
                   button1.addActionListener(this);
                   button2.addActionListener(this);
                   learn.addActionListener(this);
                   courseLabel = new JLabel();
                   pageLabel = new JLabel();
                   showLabel = createTextPane();
                   sizeLabel = new JLabel();
                   cardSetup();
                   panel[0].setBackground(Color.WHITE);
                   panel[1].setBackground(Color.WHITE);
                   panel[0].setBorder(null);
                   panel[1].setBorder(null);
                   frame = new JFrame("Flash Cards");
                   frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                   frame.setSize(485, 338);
                   frame.setLocationRelativeTo(null);
                   frame.add(panel[0], BorderLayout.CENTER);
                   frame.add(panel[1], BorderLayout.SOUTH);
                   frame.setResizable(false);
                   frame.setVisible(true);
                   start();
              catch (final Exception e)
                   e.printStackTrace();
         public Cards(final String defCourse, final String defWord,
              final String defDef, final String defPage)
              course = defCourse;
              word = defWord;
              def = defDef;
              page = defPage;
         public static void main(final String args[])
              new Cards();
         @Override
         public void actionPerformed(final ActionEvent e)
              final Object src = e.getSource();
              if (src == button1)
                   if (button1.getText().equals("Guess"))
                        button1.setText("Right");
                        button2.setText("Wrong");
                        showLabel.setText(currDef.def);
                        showLabel.setFont(bold);
                        panel[0].revalidate();
                        panel[1].revalidate();
                   else
                        allDefs = remDef(allDefs, card);
                        if (allDefs != null)
                             button1.setText("Guess");
                             button2.setText("Skip");
                             showCard();
                        else
                             if (saveDefs == null)
                                  frame.setVisible(false);
                                  if (JOptionPane
                                       .showConfirmDialog(
                                            null,
                                            "According to you, you have guessed all the words right. Would you like to start over?",
                                            "All Correct!", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
                                       allDefs = populate();
                                       start();
                                  else
                                       System.exit(0);
                             else
                                  button1.setText("Guess");
                                  button2.setText("Skip");
                                  allDefs = Arrays.copyOf(saveDefs, saveDefs.length);
                                  saveDefs = null;
                                  if (clickedWrong)
                                       clickedWrong = false;
                                       JOptionPane
                                            .showMessageDialog(
                                                 null,
                                                 "You are now going over terms that you said you guessed wrong.",
                                                 "", JOptionPane.INFORMATION_MESSAGE);
                                  showCard();
              else if (src == learn)
                   saveDefs = addDef(saveDefs, allDefs[card]);
                   allDefs = remDef(allDefs, card);
                   if (allDefs == null)
                        allDefs = Arrays.copyOf(saveDefs, saveDefs.length);
                        saveDefs = null;
                        if (clickedWrong)
                             clickedWrong = false;
                             JOptionPane
                                  .showMessageDialog(
                                       null,
                                       "You are now going over terms that you said you guessed wrong.",
                                       "", JOptionPane.INFORMATION_MESSAGE);
                   panel[0].removeAll();
                   panel[1].removeAll();
                   button1.setText("Guess");
                   button2.setText("Skip");
                   cardSetup();
                   showCard();
              else
                   if (button2.getText().equals("Wrong"))
                        int rows = 0;
                        final int colsWord = wordWrapWidth(allDefs[card].word, 21), colsDef =
                             67 - colsWord;
                        System.out.println(colsWord);
                        invis = new JButton("");
                        invis.setBackground(Color.BLACK);
                        p = new JPanel[3];
                        p[0] = new JPanel();
                        p[1] = new JPanel();
                        p[2] = new JPanel();
                        panel[0].setBackground(Color.BLACK);
                        rightWord = createTextArea(colsWord, allDefs[card].word);
                        rightDefn = createTextArea(colsDef, allDefs[card].def);
                        enterWord = createTextArea(colsWord);
                        enterDefn = createTextArea(colsDef);
                        enterWord.setBackground(Color.WHITE);
                        enterWord.setEditable(true);
                        enterWord.setFocusable(true);
                        p[0].setBackground(Color.BLACK);
                        p[1].setBackground(Color.BLACK);
                        p[2].setBackground(Color.BLACK);
                        p[0].add(rightWord);
                        p[0].add(rightDefn);
                        p[1].add(enterWord);
                        p[1].add(enterDefn);
                        p[2].add(invis); // otherwise invis appears when the word shows
                                                 // up
                        panel[0].removeAll();
                        panel[1].removeAll();
                        panel[0].revalidate();
                        panel[1].revalidate();
                        learn.setEnabled(false);
                        rightWord.setEditable(false);
                        rightDefn.setEditable(false);
                        rightWord.setBackground(Color.GREEN);
                        rightDefn.setBackground(Color.GREEN);
                        panel[0].setLayout(new GridBagLayout());
                        panel[1].setLayout(new GridBagLayout());
                        addItem("A1", 3, 1, panel[0], p[0], bold, CE, 100, 0,
                             GridBagConstraints.BOTH);
                        addItem("A2", 3, 1, panel[0], p[1], bold, CE, 100, 100,
                             GridBagConstraints.BOTH);
                        addItem("A3", 3, 1, panel[0], p[2], bold, CE, 100, 0,
                             GridBagConstraints.BOTH);
                        addItem("A1", 1, 1, panel[1], new JLabel(" "), plain, W);
                        addItem("B1", 1, 1, panel[1], learn, plain, CE);
                        addItem("C1", 1, 1, panel[1], sizeLabel, plain, E);
                        panel[0].revalidate();
                        panel[1].revalidate();
                        try
                             Thread.sleep(50);
                        catch (final Exception i)
                             i.printStackTrace();
                        rows =
                             Math.max(wordWrapLines(rightWord), wordWrapLines(rightDefn));
                        rightWord.setRows(rows);
                        rightDefn.setRows(rows);
                        enterWord.setRows(rows);
                        enterDefn.setRows(rows);
                        enterWord.requestFocus();
         public Cards[] addDef(final Cards array[], final Cards defined)
              Cards newarray[] = null;
              if (array == null)
                   newarray = new Cards[1];
              else
                   newarray = Arrays.copyOf(array, array.length + 1);
              newarray[newarray.length - 1] = defined;
              return newarray;
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan)
              addItem(cell, colSpan, rowSpan, pan, new JLabel(" "), plain, E);
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c, final Font f,
              final int anchor)
              addItem(cell, colSpan, rowSpan, pan, c, f, anchor, 100, 100);
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c, final Font f,
              final int anchor, final int weightx, final int weighty)
              addItem(cell, colSpan, rowSpan, pan, c, f, anchor, weightx, weighty,
                   GridBagConstraints.NONE);
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c, final Font f,
              final int anchor, final int weightx, final int weighty, final int fill)
              final GridBagConstraints gc =
                   new GridBagConstraints(cell.charAt(0) - 65, cell.charAt(1) - 49,
                        colSpan, rowSpan, weightx, weighty, anchor, fill, new Insets(0,
                             0, 0, 0), 0, 0);
              if (f != null)
                   c.setFont(f);
              try
                   pan.add(c, gc);
                   pan.validate();
              catch (final Exception e)
                   e.printStackTrace();
                   System.exit(0);
         public void addItem(final String cell, final int colSpan,
              final int rowSpan, final JPanel pan, final JComponent c,
              final int anchor, final int weighty, final int weightx)
              final GridBagConstraints gc =
                   new GridBagConstraints(cell.charAt(0) - 65, cell.charAt(1) - 49,
                        colSpan, rowSpan, weighty, weightx, anchor,
                        GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0);
              try
                   pan.add(c, gc);
                   pan.validate();
              catch (final Exception e)
                   e.printStackTrace();
                   System.exit(0);
         public void cardSetup()
              panel[0].setBackground(Color.WHITE);
              panel[0].setLayout(new GridLayout(3, 1));
              panel[1].setLayout(new GridBagLayout());
              final JPanel topPanel = new JPanel(new GridBagLayout()), middlePanel =
                   new JPanel(new GridBagLayout()), bottomPanel =
                   new JPanel(new GridBagLayout());
              middlePanel.setBackground(Color.GREEN);
              addItem("A1", 1, 3, topPanel);
              addItem("B1", 1, 2, topPanel);
              addItem("C1", 1, 1, topPanel);
              addItem("C2", 1, 1, topPanel, courseLabel, plain, E);
              addItem("C3", 1, 1, topPanel);
              addItem("A1", 1, 1, middlePanel, new JLabel(" "), bold, CE);
              addItem("A2", 1, 1, middlePanel, showLabel, bold, CE);
              addItem("A3", 1, 1, middlePanel, new JLabel(" "), bold, CE);
              addItem("A1", 1, 1, bottomPanel);
              addItem("B2", 1, 1, bottomPanel, pageLabel, plain, E);
              addItem("A3", 1, 1, bottomPanel);
              addItem("A1", 1, 1, panel[1]);
              addItem("B1", 1, 1, panel[1], button1, plain, E);
              addItem("C1", 1, 1, panel[1], button2, plain, W);
              addItem("D1", 1, 1, panel[1], sizeLabel, bold, E);
              panel[0].add(topPanel);
              panel[0].add(middlePanel);
              panel[0].add(bottomPanel);
         public JTextArea createTextArea(final int cols)
              return createTextArea(cols, "");
         public JTextArea createTextArea(final int cols, final String text)
              final JTextArea t = new JTextArea(text, 1, cols);
              t.addFocusListener(this);
              t.setBackground(Color.LIGHT_GRAY);
              t.setEditable(false);
              t.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,
                   null);
              t.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,
                   null);
              t.setFocusable(false);
              t.setFont(bold);
              t.setLineWrap(true);
              t.setWrapStyleWord(true);
              t.setSize(0, Short.MAX_VALUE);
              return t;
         private JTextPane createTextPane()
              final StyleContext context = new StyleContext();
              final StyledDocument document = new DefaultStyledDocument(context);
              final Style style = context.getStyle(StyleContext.DEFAULT_STYLE);
              final JTextPane textPane = new JTextPane(document);
              textPane
                   .setText("This text should wrap automatically because it is long.");
              StyleConstants.setAlignment(style, StyleConstants.ALIGN_CENTER);
              textPane.setFont(new Font("Courier New", Font.BOLD, 12));
              textPane.setEditable(false);
              textPane.setBorder(BorderFactory.createLineBorder(Color.RED));
              return textPane;
         @Override
         public void focusGained(final FocusEvent e)
              final JTextArea src = (JTextArea) e.getSource();
              src.setBackground(Color.WHITE);
              src.setCaretPosition(0);
              src.setEditable(true);
         @Override
         public void focusLost(final FocusEvent e)
              final JTextArea src = (JTextArea) e.getSource();
              boolean correct = false;
              if (src == enterWord)
                   correct = src.getText().equals(rightWord.getText());
              else if (src == enterDefn)
                   correct = src.getText().equals(rightDefn.getText());
              if (correct)
                   src.setBackground(Color.GREEN);
                   src.setEditable(false);
                   if (src == enterWord)
                        enterDefn.setFocusable(true);
                        enterDefn.setEditable(true);
                        enterDefn.requestFocus();
                   if (src == enterDefn)
                        invis.setFocusable(false);
                        learn.setEnabled(true);
                        learn.requestFocus();
              else
                   if (message)
                        if (src == enterWord)
                             int rightChars = 0;
                             for (int c = 0; c < rightWord.getText().length()
                                  && c < src.getText().length(); c++)
                                  if (rightWord.getText().charAt(c) != src.getText()
                                       .charAt(c))
                                       break;
                                  rightChars++;
                             JOptionPane.showMessageDialog(
                                  null,
                                  rightWord.getText().substring(0, rightChars)
                                       + "|"
                                       + rightWord.getText().substring(rightChars,
                                            rightWord.getText().length())
                                       + "\n"
                                       + src.getText().substring(0, rightChars)
                                       + "|"
                                       + src.getText().substring(rightChars,
                                            src.getText().length()), "Incorrect",
                                  JOptionPane.ERROR_MESSAGE);
                        if (src == enterDefn)
                             int rightChars = 0;
                             for (int c = 0; c < rightDefn.getText().length()
                                  && c < src.getText().length(); c++)
                                  if (rightDefn.getText().charAt(c) != src.getText()
                                       .charAt(c))
                                       break;
                                  rightChars++;
                             JOptionPane.showMessageDialog(
                                  null,
                                  rightDefn.getText().substring(0, rightChars)
                                       + "|"
                                       + rightDefn.getText().substring(rightChars,
                                            rightDefn.getText().length())
                                       + "\n"
                                       + src.getText().substring(0, rightChars)
                                       + "|"
                                       + src.getText().substring(rightChars,
                                            src.getText().length()), "Incorrect",
                                  JOptionPane.ERROR_MESSAGE);
                        src.requestFocus();
                   message = !message;
         public Cards[] populate()
              Cards c[] = null;
              try
                   final File file = new File("FC.txt");
                   if (file.exists())
                        final BufferedReader in =
                             new BufferedReader(new FileReader(file));
                        String line = null;
                        int badTerms = 0, goodTerms = 0;
                        while ((line = in.readLine()) != null)
                             final String lines[] = line.split("\t");
                             if (lines.length == 4)
                                  c =
                                       addDef(c, new Cards(lines[0], lines[1], lines[2],
                                            lines[3]));
                                  goodTerms++;
                             else
                                  badTerms++;
                        if (badTerms > 0)
                             JOptionPane
                                  .showMessageDialog(
                                       null,
                                       "There were "
                                            + badTerms
                                            + " bad term(s) and "
                                            + goodTerms
                                            + " good term(s). You will see only the good entries for the terms.",
                                       "There were bad terms.",
                                       JOptionPane.INFORMATION_MESSAGE);
                   else
                        JOptionPane
                             .showMessageDialog(
                                  null,
                                  "The file "
                                       + file.getCanonicalPath()
                                       + " does not exist. Please download the file or create it, and then restart the program.",
                                  "File Not Found", JOptionPane.ERROR_MESSAGE);
                        System.exit(0);
              catch (final Exception e)
                   e.printStackTrace();
              return c;
         public void printTA(final JTextArea ta)
              System.out.println("cols=" + ta.getColumns());
              System.out.println("rows=" + ta.getRows());
              System.out.println("text=" + ta.getText());
              System.out.println("getText.length()=" + ta.getText().length());
         public Cards[] remDef(final Cards[] array, final int cardnum)
              Cards temp[] = null;
              if (array.length > 1)
                   temp = new Cards[array.length - 1];
                   int defLength = 0;
                   for (int l = 0; l < array.length; l++)
                        if (!array[cardnum].equals(array[l]))
                             temp[defLength] = array[l];
                        else
                             defLength--;
                        defLength++;
              return temp;
         private void showCard()
              currDef = allDefs[(int) Math.floor(Math.random() * allDefs.length)];
              courseLabel.setText(currDef.course);
              pageLabel.setText(currDef.page);
              showLabel.setText(currDef.word);
              sizeLabel.setText("Left: " + allDefs.length);
         private void start()
              button1.setText("Guess");
              button2.setText("Skip");
              showCard();
              frame.setVisible(true);
         @Override
         public String toString()
              return "Java.lang.Cards[" + course + "," + word + "," + def + ","
                   + page + "]";
         public String wordWrap(final String string, final int w)
              String newStr = "", s = string;
              final int width = w;
              int oldSpace = 0;
              if (s.length() < w)
                   return s;
              for (int c = 0; c < s.length(); c++)
                   if (c == s.length() - 1)
                        if (s.length() > width && oldSpace != 0)
                             newStr +=
                                  s.substring(0, oldSpace).replace("(", "\\(")
                                       .replace(")", "\\)")
                                       + "<br/>" + s.substring(oldSpace + 1, s.length());
                        else
                             newStr += s;
                   else if (s.charAt(c) == ' ')
                        if (c > width)
                             newStr += s.substring(0, oldSpace) + "<br/>";
                             s =
                                  s.replaceFirst(
                                       s.substring(0, oldSpace).replace("(", "\\(")
                                            .replace(")", "\\)")
                                            + " ", "");
                             c = 0;
                        oldSpace = c;
              return newStr;
         private int wordWrapLines(final JTextArea t)
              return wordWrap(t.getText(), t.getColumns()).replaceAll("<br/>", "\n")
                   .split("\n").length;
         private int wordWrapWidth(final String s, final int w)
              final String lines[] =
                   wordWrap(s, w).replaceAll("<br/>", "\n").split("\n");
              int maxWidth = 0;
              for (final String line : lines)
                   if (line.length() > maxWidth)
                        maxWidth = line.length();
              if (maxWidth > w)
                   return w;
              return maxWidth;
    }And here is the accompanying file for Cards.java
    ET115     accuracy     the difference between the measured and accepted or "true" value of a measurement     01.04.013.2
    ET115     ampere-hour rating     a number given in ampere-hours; determined by multiplying a current in amps times the length of time in hours a battery can deliver that current to a load     03.07.093.1
    ET115     atom     the smallest element particle that possesses the unique characteristics of that element     02.01.024.1
    ET115     battery     an energy source that uses a chemical reaction to convert chemical energy into electrical energy     02.03.031.1
    ET115     charge     an electrical property of matter that exists because of an excess or deficiency of electrons     02.02.028.1
    ET115     circuit     an interconnection of a source, a load, and an interconnecting current path that are designed produce a desired result     02.06.047.1
    ET115     circuit breaker     a resettable protective device used for interrupting excessive current in an electric circuit     02.06.050.2
    ET115     colour code     a system of colour bands or dots that identify the vale of a resistor or other component     02.05.040.2
    ET115     conductance     the ability of a circuit to allow current; the reciprocal of resistance     02.05.038.3
    ET115     conductor     a material in which electrical current is established with relative ease     02.01.027.1
    ET115     coulomb     the unit of electrical charge; the total charge possessed by 6.25 * 10^18 electrons     02.02.028.2
    ET115     DMM     digital multimeter; an electronic instrument that combines meters for the measurement of voltage, current, and resistance     02.07.057.1
    ET115     electronic     related to the movement and control of free electrons in semiconductors or vacuum devices     02.01.027.3
    ET115     engineering notation     a system for representing any number as a one-, two-, or three-digit number, times a power of ten with an exponent that is a multiple of 3     01.01.007.1
    ET115     error     the difference between the true measured and best-accepted value of a measurement     01.04.013.1
    ET115     free electron     a valence electron that has broken away from its parent atom and is free to move from atom to atom within the atomic structure of a material     02.01.026.1
    ET115     fuse     a protective device that burns open when there is excessive current in a circuit     02.06.050.1
    ET115     half-splitting     a troubleshooting procedure where one starts in the middle of a circuit or system and, depending on the first measurement, works toward the output or toward the input to find the fault     03.08.096.1
    ET115     ion     an atom that has gained or lost a valence electron and resulted in a net positive or negative charge     02.01.026.2
    ET115     load     a resistor or other component that is connected across the output terminals of a circuit, draws current from the source, and has work done upon it     02.06.047.2
    ET115     metric prefix     a symbol that is used to replace the power of ten in numbers expressed in engineering notation     01.02.010.1
    ET115     Ohm's law     a law stating that current is directly proportional to voltage and inversely proportional to resistance     03.01.075.1
    ET115     orbit     the path an electron takes as it circles around the nucleus of an atom     02.01.025.2
    ET115     photovoltaic effect     the process where light energy converts directly into electrical energy     02.03.033.1
    ET115     piezoelectric effect     the property of a crystal where a changing mechanical stress produces a voltage across the crystal     02.03.034.2
    ET115     power of ten     a numerical representation consisting of a base 10 and an exponent; the number 10 raised to a power     01.01.004.2
    ET115     power rating     the maximum amount of power a resistor can dissipate without being damaged by excessive heat build-up     03.05.088.1
    ET115     precision     a measure of the repeatability or consistency of a series of measurements     01.04.013.3
    ET115     resistor     an electrical component designed specifically to have a certain amount of resistance     02.05.039.1
    ET115     round off     the process of dropping one or more digits to the right of the last significant digit in a number     01.04.015.1
    ET115     scientific notation     a system for representing any number as a number between 1 and 10 times an appropriate power of ten     01.01.004.1
    ET115     Seebeck effect     the generation of a voltage at the junction of two different metals that have a temperature difference between them     02.03.034.1
    ET115     semiconductor     a material that has a conductance value between that of a conductor and an insulator     02.01.027.2
    ET115     SI     standardised international system of units used for all engineering and scientific work; abbreviation for French Le Systeme International d'Unites     01.02.009.1
    ET115     switch     an electrical or electronic device for opening and closing a current path     02.06.048.4
    ET115     thermistor     a type of temperature transducer in which resistance is inversely proportional to temperature     02.05.046.2
    ET115     thermocouple     a thermoelectric type of voltage source that is commonly used to sense temperature     02.03.033.4
    ET115     troubleshooting     a systematic process of isolating, identifying, and correcting a fault in a circuit or system     03.08.095.1
    ET115     voltage     the amount of energy available to move a certain number of electrons from one point or another in an electrical circuit     02.03.029.Edited by: ElectrifiedBrain on Apr 12, 2011 12:08 AM

    EJP wrote:
    No way anybody in their right mind is going to look at all that. Find the salient differences between your SCCE and your non-working code.I didn't think so, but it was worth a shot. I did my best to find it last night, but I just couldn't.
    Kleopatra wrote:
    hahahaha ... you really think that'll work: "I'm tired, so going for a nap - hope you'll clean the mess and have it fixed when I wakeup"
    Dream well
    JeanetteIt was midnight, and I had to wake up at 5:30, so that was true. I didn't really think it was going to work, but I was hoping.
    Anyway, this can be locked too, I guess. I have an idea on how to find what's wrong.

Maybe you are looking for