JTextPane and Clipboard

Hi!
I am using JDK 1.3 and JDK 1.4 and I've got the following question:
If I use the javax.swing.JTextPane object, I can define a javax.swing.text.DefaultEditorKit and other actions in order to implement copy/paste functionality. My question is: Which clipboard is used here? The java api documentation of javax.swing.text.DefaultEditorKit.PasteAction states that the system clipboard is used.
But this particular applet I am using is not permitted to use the system clipboard, I cannot get the system clipboard from java.awt.Toolkit, it throws an exception.
The reason for me writing the question into that forum is that I want to manually access the clipboard that is used by my JTextPane object.
Ciao
Tobi

Read the discussions at the link shown below especially my reply #11:
http://forum.java.sun.com/thread.jsp?forum=57&thread=355974
;o)
V.V.

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.

  • My Intermedia Web agent and Clipboard doesn't work!

    Hi,Simon
    I'v just downloaded the Intermedia Web agent and Clipboard plugin from OTN a few days ago.But both of it don't work when I install it.Would you please help me look for the reason?
    My operating system is Windows 2000 Professional,and my web server is OAS 4.0.8.1,and my database is 8i.
    When I visit these address"http://host:port/intermedia/^about"and "http://host:port/intermedia/admin",the browser returns to me a error page.
    When I connect to host in Clipborad,it returns to me an error message which says"The following error was received from the intermedia web agent,<HTML><HEAD><TITLE>Invalid host specified</TITLE></HEAD><BODY>The request did not specify a valid virtual host</BODY>
    I don't know if this web agent can work with OAS 4.0.8.1 and if OAS 4.0.8.1 can run in the Windows 2000 Professional.
    Thanks
    null

    Hi,Simon,
    Thank you for your help!I have sent my application information to your product manager by email!
    But the error stll appears.When I typed the whole domain name in the host area of Clipborad,the error message changed to "An application error has occured,please try again!".When I typed the address"http://My host:port/intermedia/~about"(I have substituted ^ with ~ )"and "http://My host:port/intermedia/admin",it still returns an error page which says"HTTP 500 Server internal error......"like before!
    Also,I found other errors about OAS.One Application cannot add the second Cartridge,it returns an error:"OWS-09103:Cartridge section'[Application wscWRBApp" when I do it.So I suspect the reason is my operating system platform,I will try to reinstall it now.
    Regards!
    Reemon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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 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 Copy and paste

    Hi All,
    I have a JTextPane inside applet and It doesn't seem to copy anything outside the applet.
    Is there any way to copy and paste the content outside the applet ??

    There are security restrictions in place with applets. Since an applet is a foreign object downloaded to your PC, it has limited access to PC components such as the Clipboard.
    You need to digitally sign your Applet. I have always had problems with the clipboard and applets even after signing them. I found that newer version of Java Plugin still did not allow me to copy and paste to/from a swing component.
    I hope you have better luck.

  • About JtextPane And Jtext Editor

    Hello,
    I want Copy some text from Jtextpane or JtextEditor with HTML contents.
    I means If some Web Page are displayed on JtextPane as like "Hello world".
    When i copy the text i want it with Tag information
    <em>Hello World</em>. Is it possible with Jtext Pane.
    By the Way from IE6.0 when we copy some text and Paste it on MSword, it display the text with as like as it was Web pages.
    How MSword Knows the TAg Information from the Clipboard?
    Best Regards of Forward.
    Dimitra

    but why the SimHIPPI.java can not invoke the method sumInfo()
    I don't know, but that is not the right place for your code.
    The paintComponent() method is invoked by the RepaintManager, whenever it determines a component needs to be repainted. This means the component may repaint itself when you aren't expecting it to be painted.
    Code like that should be invoked from the Timer.

  • JTable and clipboard...

    Hi all!
    I'm trying to copy data from JTable to system clipboard. Here's my code that is
    supposed to do that except it doesn't work. Nothing happens. The system is
    Windows, rigth click invokes menu with only one position - COPY, which is served
    by a appopriate ActionListener. I want to copy entire table (all data):
    private class NotEditableTable extends JTable
    NotEditableTable(Object[][] data, Object[] columnNames)
    super(data, columnNames);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    setCellSelectionEnabled(true);
    getTableHeader().setReorderingAllowed(false);
    NotEditableTableEngine nete = new NotEditableTableEngine();
    this.addMouseListener(nete);
    public boolean isCellEditable(int row, int column)
    return false;
    private class NotEditableTableEngine extends MouseAdapter implements ActionListener
    public void mouseReleased(MouseEvent e)
    if (e.isPopupTrigger())
    JPopupMenu menu = new JPopupMenu();
    JMenuItem menuitem = new JMenuItem(Lang.TABLE_COPY, new ImageIcon("res/Copy16.gif"));
    menuitem.addActionListener(this);
    menu.add(menuitem);
    menu.show(NotEditableTable.this, e.getX(), e.getY());
    public void actionPerformed(ActionEvent e)
    TransferHandler th = new TransferHandler(null);
    NotEditableTable.this.setTransferHandler(th);
    Clipboard clip = NotEditableTable.this.getToolkit().getSystemClipboard();
    th.exportToClipboard(NotEditableTable.this, clip, TransferHandler.COPY);
    }

    I also tried the code above with a simple JTextField, both with text selected and not.Did my sample code use the TransferHandler??? The simple way to do it for a JTextField would be
    Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
    StringSelection testData = new StringSelection( textField.getText );
    //StringSelection testData = new StringSelection( textField.getSelectedText );
    c.setContents(testData, testData);
    As for the table I said that the Ctrl-C KeyStroke will invoke the default Action to copy selected data from the JTable to the Clipboard. This can be tested manually by simply using Ctrl-C. If you want to invoke it in your program then you need to get the corresponding Action from the JTable and invoke the ActionPerformed method of the Action. You can try using the
    getActionForKeyStroke(...) method of JComponent to get the Action.

  • 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 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");

Maybe you are looking for

  • What does "Other" mean for iPhone storage?

    My other section in the iPhone keeps on growing every week. Now it's 4.7 GB, more than apps, audio, video, photo... how do I understand what's in there? Any way to see the detail?

  • My iPod says 20%, and when it's at 10% says it's at 20%.

    This has been happening since last year. Every time my iPod Touch 4g is at 20%, it's at 20%, but when it's at 10%, it says 20% battery remaining. (It's an OCD thing)

  • RoboHelp 7 Takes 30 minutes to Load Project

    I am working on a large project and I'm finding that since upgrading to version 7 my project is taking 10 times longer to load. When I select teh project I want to work on it takes half an hour for the program to be ready for me to get to work. Is th

  • Oracle trainin

    I am a web develper that just got a new schema (created by our DBA) where I need to create objects such as Tables, Queries, Constraints and maybe some triggers in an Oracle 9i database. Please advise what class I should start with on Oracle's Trainin

  • What to monitor on testing phase

    We are planning to put in production one ApEx app (2.2.0.1) on Oracle 10gR2.1. We know that this monitoring phase will be very important. We are able to monitor db side (classic DBA task) but we are not sure what to monitor on ApEx and Apache-shortly