JTextPane and viewports

Hi,
I asked this question before but I may have made it too complex a question and may have confused some of you so I'll ask it a little differently.
Here is what I would like to do. Lets say I define a JTextPane to be 10 inches wide and 10 inches in height, but I would only like the viewable area to be only 5x5 inches wide at a time. I want to be able to view the entire JtextPane, but only in 5" by 5" viewable window. When I get to the far right side, or bottom of the viewable window, the window would then move with my next arrow key press. Can someone tell me if this is possible. I've tried some things with scrollbars and a JScrollpane with no luck. I have to have the ability to stop the user when they reach their 10 inch margin and once I introduce scroll bars, there is no way to stop them at 10 inches. This problem comes from the fact that I want to be able to define a Jtextpane to be larger than the screen size someone is limited too, but I still want to limit it to 10 inches. Any ideas at all???
Joe Crew

Denis,
I thought I would post this as a guide to anyone else having the same problem. Not shown below is where I created a BorderLayout and my own personal toolbar for text editing commands which I added to the "North" border. Here is the pseudocode for creating a JTextPane that you can create at a size larger than your PC screen size, have scrollbars, and still limit the width of the JTextPane area. The paradox was once I turn on scrollbars I could no longer limit the size of the JTextPane. Note that in main() not shown here I specified the application to have a setSize of 640x480.
<CODE>
private void setScrollBars() {
// These next few variables were actually declared in another
// part of the overall application, I just added them here
// for the sake of clarity. p1 was used for my toolbar,
// thus p2 is shown here.
JPanel p2 = new JPanel();
JTextPane jpane = new JTextPane();          
Dimension myDim = new Dimension();
myDim.setSize(1000, 1000);          
jpane.setPreferredSize(myDim);
p2.add(jpane);
jscroll = new JScrollPane(p2);
jscroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
jscroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
add(jscroll, "Center" );
</CODE>
The mistake I made previously, which I am sure could still be fixed by someone, was I added the JTextPane to the JScrollbar, then added the JScrollbar to the JPanel. I could not control the actual size of the JTextPane width or height this way. By adding the JtextPane to the Panel and then adding the panel to the JScrollPane, the panel does all of the scrolling and I can specify the exact size of the JTextPane I want. You also don't have to do any monkey business with moving viewports around this way either.
One issue yet to be addressed by this method is even though you can't see the text beyond the area you create for the JTextPane, text still gets entered past the horizontal limit. I'm working on that issue as I type this, but I wanted to at least post the main solution before this original post got too outdated.
joberoni

Similar Messages

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

  • Obnoxious JTextPane and JScrollPane problem.

    I have written a Tailing program. All works great except for one really annoying issue with my JScollPane. I will do my best to explain the problem:
    The program will continue tailing a file and adding the text to the JTextPane. When a user scrolls up on the JScrollPane, the program still adds the text to the bottom of the JTextPane and the user can continue to view what they need.
    Here is the problem: I have text being colored throughout the text pane. For instance, the word ERROR will be in red. The problem is when the program colors the text, it moves the scroll pane to the line where word that was colored is at. I don't want that. If the user moves the scroll bar, I want the scroll bar to always stay there. I don't want the program to move to the text that was just colored.
    Is there a way to turn that off? I can't find anything like that anywhere.

    Coloring text will not cause the scrollpane to scroll.
    You must be playing with the caret position or something.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • JTextPane and Horizontal Scrollbars

    Hi there,
    I had written an app that included an Event Log, and all was good in my
    world.
    Then one of the app users commented they would like errors to stand out within the log!
    I said "No Problem" but it turns out to be a major bloody headache!!!!!
    I was using a JTextArea but after reading some posts on this forum I decided to use a JTextPane. I found some code for changing the font colour, and everything appeared to be working fine ;-)
    ...until that is I realised my HORIZONTAL_SCROLLBAR_AS_NEEDED was never needed as the text had started to wrap ;-(
    I have tried searching this site and none of the suggestions work for me, the vertical scroll works fine - and I am really stuck. Therefore:
    Is there a way to get the Horizontal scroll bar working in a JTextPane?
    Is there an alternative to JTextPane that will allow me to control font colour by line?
    Do you even know what I am harping on about?
    Or should I admit defeat and add a second JTextArea and a button to switch between my two event types??
    Any suggestions would be greatly received!
    P.S. Below is the edited code that I think is responsible for my problem :0)
    public class EventLogGUI extends JPanel
    private JPanel jpLog = new JPanel();
    private StyledDocument sdLog = new DefaultStyledDocument();
    private JTextPane jtpLog = new JTextPane( sdLog );
    private MutableAttributeSet mas = new SimpleAttributeSet();
    private JScrollPane jspLog;
              public EventLogGUI()
              this.setBounds( 5, 7, 407, 256 );
              this.setBorder( BorderFactory.createLoweredBevelBorder() );
              this.setLayout( null );
              this.add( jpLog );
              jspLog = new JScrollPane( jtpLog,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
              jspLog.setBounds( 12, 25, 372, 180 );
              jpLog.setLayout( null );
              jpLog.setBounds( 5, 5, 397, 218 );
              jpLog.add( jspLog );
              jtpLog.setEditable( false );
              jtpLog.setMargin( new Insets ( 2, 2, 2, 2 ) );
              public void initialiseGUI()
              Vector events = uploadEventLog();
              String event;
              jtpLog.setText( "" );
                        for ( int i = 0; i < events.size(); i++ )
                        event = "" + events.elementAt( i );
                                  if ( event.length() >= 8 && event.substring( 0, 8 ).equals( "WARNING:" ) )
                                            StyleConstants.setForeground( mas, Color.red );
                                  else
                                            StyleConstants.setForeground( mas, Color.black );
                                  try
                                  sdLog.insertString( sdLog.getLength(), event + "\n", mas );
                                  catch( Exception e )
    }

    Hi!
    just wondered if you've searched the forum already. If not: always do that before posting.
    I searched and found this helpful:
    http://forum&threadID=256602
    the solution found in that thread is to extend the JTextPane and add a setLineWrap-method:
    class JTextWrapPane extends JTextPane {
        boolean wrapState = true;
        JTextArea j = new JTextArea();
         * Constructor
        JTextWrapPane() {
            super();
        public JTextWrapPane(StyledDocument p_oSdLog) {
            super(p_oSdLog);
        public boolean getScrollableTracksViewportWidth() {
            return wrapState;
        public void setLineWrap(boolean wrap) {
            wrapState = wrap;
        public boolean getLineWrap(boolean wrap) {
            return wrapState;
    }  now you can use JTextWrapPane instead of JTextPane:
    //  instead of   private JTextPane jtpLog = new JTextPane( sdLog );
        private JTextWrapPane jtpLog = new JTextWrapPane( sdLog );and set JTextWrapPane.setLineWrap(false):
            jtpLog.setLineWrap(false);It may not be the non plus ultra, but it seamed to work for me. ;)

  • JTextPane and highlighting

    Hello!
    Here's what I'm trying to do: I have a window that needs to display String data which is constantly being pumped in from a background thread. Each String that comes in represents either "sent" or "recieved" data. The customer wants to see sent and recieved data together, but needs a way to differentiate between them. Since the Strings are being concatinated together into a JTextPane, I need to highlight the background of each String with a color that represents whether it is "sent" (red) or "recieved" (blue) data. Should be easy right? Well, not really...
    Before I describe the problem I'm having, here is a small example of my highlighting code for reference:
         private DefaultStyledDocument doc = new DefaultStyledDocument();
         private JTextPane txtTest = new JTextPane(doc);
         private Random random = new Random();
         private void appendLong() throws BadLocationException {
              String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
              int start = doc.getLength();
              doc.insertString(doc.getLength(), str, null);
              int end = doc.getLength();
              txtTest.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
         private Color randomColor() {
              int r = intRand(0, 255);
              int g = intRand(0, 255);
              int b = intRand(0, 255);
              return new Color(r, g, b);
         private int intRand(int low, int hi) {
              return random.nextInt(hi - low + 1) + low;
         }As you can see, what I'm trying to do is append a String to the JTextPane and highlight the new String with a random color (for testing). But this code doesn't work as expected. The first String works great, but every subsequent String I append seems to inherit the same highlight color as the first one. So with this code the entire document contents will be highlighted with the same color.
    I can fix this problem by changing the insert line to this:
    doc.insertString(doc.getLength()+1, str, null);With that change in place, every new String gets its own color and it all works great - except that now there's a newline character at the beginning of the document which creates a blank line at the top of the JTextPane and makes it look like I didn't process some of the incomming data.
    I've tried in veign to hack that newline character away. For example:
              if (doc.getLength() == 0) {
                   doc.insertString(doc.getLength(), str, null);
              } else {
                   doc.insertString(doc.getLength()+1, str, null);
              } But that causes the 2nd String to begin on a whole new line, instead of continuing on the first line like it should. All the subsequent appends work good though.
    I've also tried:
    txtTest.setText(txtTest.getText()+str);That makes all the text line up correctly, but then all the previous highlighting is lost. The only String that's ever highlighted is the last one.
    I'm getting close to submitting a bug report on this, but I should see if anyone here can help first. Any ideas are much appreciated!

    It may work but it is nowhere near the correct
    solution.It seems to me the "correct" solution would be for Sun to fix the issue, because it seems they are secretly inserting a newline character into my Document. Here's a compilable program that shows what I mean:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultHighlighter;
    import javax.swing.text.DefaultStyledDocument;
    public class TestFrame extends JFrame {
         private JButton btnAppend = new JButton("Append");
         private DefaultStyledDocument doc = new DefaultStyledDocument();
         private JTextPane txtPane = new JTextPane(doc);
         private Random random = new Random();
         public TestFrame() {
              setSize(640, 480);
              setLocationRelativeTo(null);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        dispose();
              getContentPane().add(new JScrollPane(txtPane), BorderLayout.CENTER);
              getContentPane().add(btnAppend, BorderLayout.SOUTH);
              btnAppend.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doBtnAppend();
         private void doBtnAppend() {
              try {
                   String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
                   int start = doc.getLength();
                    * This line causes all highlights to have the same color,
                    * but the text correctly starts on the first line.
                   doc.insertString(doc.getLength(), str, null);
                    * This line causes all highlights to have the correct
                    * (different) colors, but the text incorrectly starts
                    * on the 2nd line.
    //               doc.insertString(doc.getLength()+1, str, null);
                    * This if/else solution causes the 2nd appended text to
                    * incorrectly start on the 2nd line, instead of being
                    * concatinated with the existing text on the first line.
                    * (a newline character is somehow inserted after the first
                    * line)
    //               if (doc.getLength() == 0) {
    //                    doc.insertString(doc.getLength(), str, null);
    //               } else {
    //                    doc.insertString(doc.getLength()+1, str, null);
                   int end = doc.getLength();
                   txtPane.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
              } catch (BadLocationException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        new TestFrame().setVisible(true);
         private Color randomColor() { return new Color(intRand(0, 255), intRand(0, 255), intRand(0, 255)); }
         private int intRand(int low, int high) { return random.nextInt(high - low + 1) + low; }
    }Try each of the document insert lines in the doBtnAppend method and watch what it does. (comment out the other 2 of course)
    It wastes resources and is inefficient. A lot of work
    goes on behind the scenes to create and populate a
    Document.I tracked the start and end times in a thread loop to benchmark it, and most of the time the difference is 0 ms. When the document gets to about 7000 characters I start seeing delays on the order of 60 ms, but I'm stripping off text from the beginning to limit the max size to 10000. It might be worse on slower computers, but without a "correct" and working solution it's the best I can come up with. =)

  • JTextPane and the direction of "textflow"

    Hi, I got a kinda strange question.
    What i want to do is to make the text in a JtextPane go from bottom and move up. The textpane wont be editable for the user.
    That is: The text should show up at the bottom of the view and move up in the view as more text is added.
    I could solve this somewhat unintelligent by adding an invisible box (Box.createVerticalStrut ) at the beginning of the text. The height would be the same as the viewport the textpane is inside. But are there more elegant solution? Scrollbars would be added as soon as the first line is entered into the textpane, and thats a less than ideal solution.

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

  • Word wrapping with JTextPane and styleDocument

    Hello,
    Can someone help me with the following problem.
    I have a JTextPane where i add a styledDocument.
    If i fill this with text it doen't word-warp the text!
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.Style;
    import javax.swing.text.StyledDocument;
    public class LogField extends JTextPane implements LogFileTailerListener{
         public static StyledDocument doc;
         private LogFileTailer tailer;
         private TextStyles styles;
         public LogField(){
              this.setEditable(false);
              this.setContentType("text/html");
              doc = (StyledDocument)this.getDocument();
              styles = new TextStyles();
              tailer = new LogFileTailer( LogPanel.logFileName, 1000, true );
              tailer.addLogFileTailerListener( this );
             tailer.start();          
         public void addText(String text, Style style){     
               try {
                  text = text + System.getProperty("line.separator");
                   doc.insertString(doc.getLength(), text, style);
              } catch (BadLocationException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              this.setCaretPosition(doc.getLength());
         @Override
         public void newLogFileLine(String line) {
                addText(line,styles.getDefaultStyle());
    }

    Since you are simply appending text to the Document you should not be using a type of "text/html".
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Saving RTF from JTextPane and missing subscripts

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

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

  • JTextPane and TransferHandler

    While trying to integrate another company's applet into our system, I realized I was going to have to write my own TransferHandler to handle pasting content from Microsoft Word. Soon after, I realized that you must also override other methods of TransferHandler so that copying, cutting and drag-and-drop all still work. I have been able to get most things working, but have had trouble with the createTransferable() method. The problem I am having is that the JComponent I am trying to allow copying from is a JTextPane with and underlying HTMLDocument. When I use the JTextPane.getSelectedText() method, I only get the bare text and not the underlying HTML code that I desire.
    I have searched high and low for a method to get the underlying HTML code which corresponds to the current selection in the JTextPane to no avail. Can anyone offer any insight into this conundrum?
    Thank you for your time and consideration.

    It's funny that no one has ever answered this question (or the many like it from before). I ended up finding the source for Java's default TransferHandler and seeing how it was grabbing the underlying HTML code. It all seems to make much more sense now, but it's not something I would have arrived at without the source to look at.
    You can find the source to the BasicTextUI.TextTransferHandler here -- http://www.javaresearch.org/source/jdk142/javax/swing/plaf/basic/BasicTextUI.java.html. Among other things, it shows how you go about "grabbing" the structure from the underlying document. Basically you use the EditorKit (or, in this case, the HTMLEditorKit) to read from the document and it take care of the "translation" for you. The important part goes something like this (minus try-catch blocks):
    Document doc = textPane.getDocument();
    EditorKit kit = textPane.getEditorKit();
    int beg = textPane.getSelectionStart();
    int end = textPane.getSelectionEnd();
    Position p0 = doc.createPosition(beg);
    Position p1 = doc.createPosition(end);
    StringWriter htmlOut = new StringWriter(p1.getOffset() - p0.getOffset());
    kit.write(htmlOut, doc, p0.getOffset(), p1.getOffset() - p0.getOffset());
    return htmlOut.toString();Now the only problem I need fixed is trying to get the EditorKit to stop from including all the structure from the entire ancestry of the current selection. For instance, if you select just one letter from a cell of a table that is nested in a div, inside another table, the resulting string from that single-character selection would be like this:
    <html xmlns="http://www.w3.org/1999/xhtml">
    <body>
    <table>
    <tr>
    <td>
    <div>
    <table><tr><td>X</td></tr></table>
    </div>
    </td>
    </tr>
    </table>
    </body>
    </html>Now if someone could just point out how to intelligently limit that return scope, I'd be one happy little coder! (I tried, unsuccessfully, to insert a marker like following, to no avail.)
    <!--Begin Marker-->
    the original selection goes here
    <!--End Marker-->

  • JTextPane and the default PasteAction

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

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

  • JTextPane and RTF line returns

    I'm wondering is there anyway to use a line return with JTextPane's? I'm not sure if thats what they're called but what i'm talking about is the RTF equivelent of <BR>. I tried importing a file with line returns and none of they were treated as a space. I also tried typing shift-enter like in word, but that didn't do anything. Is it possible to use line returns with a jtextpane? or is that just something you have to do without?

    Okay here's my code:
         coursetext = new JTextPane();
         coursetext.setContentType("text/RTF");
         RTFEditorKit edkit = new RTFEditorKit();
         coursetext.setEditorKit(edkit);
    and later on:
         RTFEditorKit edkit = new RTFEditorKit();
         File file = new File("gn.rtf");
         try {
              FileInputStream fr = new FileInputStream(file);     
              DefaultStyledDocument doc = new DefaultStyledDocument();
              edkit.read(fr,doc, 0);
              coursetext.setStyledDocument(doc);
    The file i'm loading is saved as an RTF file from Wordpad. If i try to load a rtf file saved from MS Word (2003) it gives me a null pointer exception.

  • TableCellRenderer with JTextPane and HTML

    I'm writing a TableCellRenderer that will be rendering HTML content using a custom extension to the JTextPane class. Where I'm having trouble is in calculating the necessary height to set the table row based on the content of the cell (in this case HTML text in my JTextPane component). I know the width of the table cell and I can figure out the width of the content (taking into account the formatting because of the HTML content). This all works perfectly until the column width shrinks enough to cause the underlying view to word wrap.
    Here is the code snippet from my JTextPane to count the number of lines of text and calculate the width of the content
      public int getWidthOfContent() {
        getLineCount();
        return m_iWidthOfContent;
      public int getWidthOfContent(int p_iWidthOfArea) {
        getLineCount(p_iWidthOfArea);
        return m_iWidthOfContent;
      public int getLineCount(int iComponentWidth) {
        int iWidth = 0;
        int iBreakCount = 0;
        int iHardBreakCount = 0;
        int iTotalWidth = 0;
        int iTotalContentWidth = 0;
        int iMaxHeight = 0;
        Document doc = getDocument();
        ElementIterator it = new ElementIterator(doc.getDefaultRootElement());
        StyleSheet styleSheet = null;
        if(doc instanceof HTMLDocument) {
          styleSheet = ((HTMLDocument)doc).getStyleSheet();
        if(iComponentWidth == -1) {
          iWidth = getWidth();
        else {
          iWidth = iComponentWidth;
        Element e;
        while ((e=it.next()) != null) {
          AttributeSet attributes = e.getAttributes();
          Enumeration enumeration = attributes.getAttributeNames();
          boolean bBreakDetected = false;
          while(enumeration.hasMoreElements()) {
            Object objName = enumeration.nextElement();
            Object objAttr = attributes.getAttribute(objName);
            if(objAttr instanceof HTML.Tag) {
              HTML.Tag tag = (HTML.Tag)objAttr;
    //          if(tag == HTML.Tag.BODY) {
    //            UCSParagraphView pv = new UCSParagraphView(e);
    //            if(pv.willWidthBreakView(iWidth)) {
    //              iHardBreakCount++;
              FontMetrics fontMetrics = null;
              if(styleSheet != null && styleSheet.getFont(attributes) != null) {
                fontMetrics = getFontMetrics(styleSheet.getFont(attributes));
              if(fontMetrics != null && fontMetrics.getHeight() > iMaxHeight) {
                iMaxHeight = fontMetrics.getHeight();
              if(tag.breaksFlow()) {
                //This must be a breaking tag....this will add another line to the count
                bBreakDetected = true;
                if(tag.equals(HTML.Tag.BR) || tag.isBlock() && (!tag.equals(HTML.Tag.HEAD) && !tag.equals(HTML.Tag.BODY))) {
                  if(iTotalContentWidth == 0) {
                    iTotalContentWidth = iTotalWidth;
                    iTotalWidth = 0;
                  else if(iTotalWidth > iTotalContentWidth) {
                    iTotalContentWidth = iTotalWidth;
                    iTotalWidth = 0;
                  else {
                    iTotalWidth = 0;
                  if(tag.equals(HTML.Tag.H1) || tag.equals(HTML.Tag.H2) || tag.equals(HTML.Tag.H3) || tag.equals(HTML.Tag.H4)) {
                    iHardBreakCount += 3; //These count as three lines (Blank - Content - Blank)
                  else {
                    iHardBreakCount++;
                iBreakCount++;
          if(!bBreakDetected) {
            Font font;
            FontMetrics fontMetrics;
            if(e.getDocument() instanceof HTMLDocument) {
              font = ((HTMLDocument)e.getDocument()).getStyleSheet().getFont(e.getAttributes());
              fontMetrics = getFontMetrics(font);
            else {
              font = getFont();
              fontMetrics = getFontMetrics(font);
            int iRangeStart = e.getStartOffset();
            int iRangeEnd = e.getEndOffset();
            if(fontMetrics.getHeight() > iMaxHeight) {
              iMaxHeight = fontMetrics.getHeight();
            if(e.isLeaf()) {
              String strText;
              try {
                strText = this.getText(iRangeStart, iRangeEnd - iRangeStart);
                if(strText.equals("\n")) {
                  //iBreakCount++;
                iTotalWidth += SwingUtilities.computeStringWidth(fontMetrics, strText);
              catch (BadLocationException ex) {
                //Something happened.....don't care....just eat the exception
        m_iMaxFontHeight = iMaxHeight;
        m_iWidthOfContent = iTotalWidth;
        m_iHardBreakCount = iHardBreakCount;
        if(iWidth > 0) {
          int iLineCount = (iTotalWidth / iWidth) + iBreakCount;
          return iLineCount;
        return 1;
      }And here is the code from my TableCellRenderer that uses the above information
       public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                                                      boolean hasFocus, int row, int column) {
         if(ValidationHelper.hasText(value) && value.toString().indexOf("<html>") != -1) {
           UCSHTMLTextPane pane = new UCSHTMLTextPane();
           pane.setText(ValidationHelper.getTrimmedText(value.toString()));
           BigDecimal lWidthCell = new BigDecimal(table.getCellRect(row, column, false).getWidth() - 15);
           BigDecimal lWidthContent = new BigDecimal(pane.getWidthOfContent(lWidthCell.intValue()));
           int iHardBreakCount = pane.getHardBreakCount();
           BigDecimal lLineCount = lWidthContent.divide(lWidthCell, BigDecimal.ROUND_CEILING);
           int iLineCount = lLineCount.intValue();
           double dWidthCell = lWidthCell.doubleValue();
           double dWidthContent = lWidthContent.doubleValue();
           double dWidthContentPlusFivePercent = dWidthContent + (dWidthContent * .01);
           double dWidthContentMinumFivePercent = dWidthContent - (dWidthContent * .01);
           if(dWidthCell >= dWidthContentMinumFivePercent && dWidthCell <= dWidthContentPlusFivePercent) {
             iLineCount++;
           iLineCount += iHardBreakCount;
           int iMaxFontHeight = pane.getMaxFontHeight();
           int iHeight = (iMaxFontHeight * iLineCount) + 5;
           if ( (iLineCount > 0) && (table.getRowHeight(row) != iHeight)) {
             pane.setPreferredSize(new Dimension(0, iHeight));
             if(m_bAutoAdjustHeight) {
               table.setRowHeight(row, iHeight);
           if(iLineCount == 1) {
             if(iHeight != table.getRowHeight()) {
               if(m_bAutoAdjustHeight) {
                 table.setRowHeight(iHeight);
           setComponentUI(pane, table, row, column, isSelected, hasFocus);
           return pane;
    }Any suggestions?

    Hello,
    You must initialize correctly your JTextPane like this:
    javax.swing.text.html.HTMLEditorKit htmlEditorKit = new javax.swing.text.html.HTMLEditorKit();
    javax.swing.text.html.HTMLDocument htmlDoc = (javax.swing.text.html.HTMLDocument)htmlEditorKit.createDefaultDocument();
    setEditorKit(htmlEditorKit);
    setDocument(htmlDoc);
    setEditable(true);
    setContentType("text/html");

  • JTextPane and XMLParser and jdk .-) problems

    Hi there.
    I have a nice problem, which really gives me headaches.
    I have an XML editor (working as an applet or as an aplication, using a JTextPane). All worked ok untill jdk1.3 and parts even until jdk1.4. Now 2 big problems appeared.
    1.Under jdk1.4.1:
    Spaces between lines are awful big. The actual characters are ok, but the cursor is almost twice as the characters. The distance from the bottom of a character and the bottom of the line is pretty big. Now that looked to me as a SpaceBelow or LineSpacing problem. I've tried to set up the SpaceBelow or/and LineSpacing... everything that I've thought it should work. No result. Seems like they have no effect when XMLParser comes in place and sets up the document content (at least i think this is the reason, also i'm not sure). An element tree implemented shows me that this attributes are set to the values I've intended, but no 'visual' effect. Does anyone know ANYTHING about this? Please!
    2.Starting from jdk1.3. Doubling of tags.
    If the XML editor reads something like <FT>something</FT> from a xml file, it sets in the JTextPane <FT><FT>something</FT></FT>. It's working under jdk1.2 but if I switch to 1.3 or 1.4does something like this. Any idea what's going on? Could it be an unfortunate mix between jdk and xalan libraries?
    I REALLY hope that ANYONE of you knows ANYTHING about these!!!
    THNX!

    Hi DrClap.
    Well, this would be the best thing to do. The only problem is that those are long time gone. Not really 'gone', but they are not to be found.
    There's something about first problem: At the end of starting process, after the parser finished his work, if I come and set the attributes (in the document of the JTextPane, using StyleConstants) with replace set to true, the display is ok but, of course, I loose any style defined in the xml file. That means is not a problem of the JTextPane in jdk 1.4 (at one time I thought it might be a 'mapping' problem of the JTP in 1.4) or?
    Because I'm really stuck, I have all kind of strange ideas!!!
    Could be "old libraries(for the parser) - new jdk" mixture problem, perhaps? (I've told you!)
    THX for your previous response.

  • How to display bold text in JTextPane and how to get them?

    I need show some fonted text like BOLD, UNDER LINE, can some body tell how to do it? for example, how to show the following sentences?
    "This is <b><u><i>This is a test of the formatting option</b></i></u> end of"
    in JTextPane?

    Hi Juergen,
    I found Your blog and found it  really interesting... though I was not able to use it: I (like Jun Li is asking, I guess) need to use a dynamic text, containing formatting informations (according the xhtml syntax).
    I tried to pass it to the form by an ABAP-dictionary based interface and by means of the context (in a webdynpro page), but both tries failed.
    Some suggestion will be greatly appreciated.
    Thankyou
    Simone

  • JScrollPane, JTextPane and JPanel... wtf?

    i am working on a extending a JPanel to have a JTextPane in a JScrollPane. When i add the JTextPane to the JScrollPane inside of the JPanel object it doesn't scroll horizontally, but when i add the whole panel to a JScrollPane in the JFrame that i have testing it, it does scroll horizontally, the JScrollPane in both instances the JScrollBar has both horizontal and vertical scrolling set to as needed.
    why is this happening?

    Thanks for your answers!
    Revalidating did the trick, however I still have a problem with the JScrollPane... I created a new JScrollPane and wrote so:
    myScrollPane = new JScrollPane(internalPanel);
    myScrollPane.setPreferredSize(new java.awt.Dimension(2, 205));
    myScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    //Added Code
    handScrollPane.setViewportView(handPanel);
    //End Added Code
    mainPanel.add(myScrollPane, BorderLayout.SOUTH);Then whenever items were added to the internalPanel I changed the scroll-bar's maximum value to the height of the internalPanel by writing:
    myScrollPane.getVerticalScrollBar().setMaximum(internalPanel.getHeight());But when I run my application, the scroll-bar's maximum value doesn't change even though items are added to the internalPanel. Why is this?
    With Thanks,
    laginimaineb.
    B.U.M.P (Sorry)

Maybe you are looking for

  • IPod updates a lot of songs with no apparent reason

    Since today I've noticed that every time I plug my 5g 30GB iPod in, iTunes updates about 5GB of songs with no reason. I didn't touch the songs in the meantime. I found somebody else with the same problem in the forums, but with no solution. I don't u

  • DELETED rows from internal table

    Hi Experts, If I delete row/s from an internal table using the command DELETE ADJACENT DUPLICATES, is there a way to get these deleted rows. Thanks in advance. Rose

  • QUICKTIME MEMORY LEAK ???

    Hi, I'm developing an application in DMX2004 and its got lots of QTVRS (version 7). There's one feature which starts the automatic schematic tour of all the VRs. I noticed that as the sprite's member is changed with a new QTVR, there is a substantial

  • .mov opened in PSE CS5, saved as .psd, now PSE won't reopen it

    I'm working on masking some video, and figured out a workflow that starts in Photoshop Extended CS5 and then moves to After Effects CS5. As instructed by this Adobe tutorial, I can do this by opening my footage (.mov's) in PSE, saving as a .psd, then

  • Flash 6 vs. Flash 7/8 AS1 difference?

    Is this behavior documented? It has left me utterly baffled. var a = "string"; if(!a)trace("!a:"+a); Working in the Flash 8 IDE, I get these results: Publish settings - Flash 6 AS1 Output - "!a:string" Publish settings - Flash 7 or 8 AS1 Output - ""