Text Problem in JTextPane

im trying to save some unicode characters and images from a JTextPane
in jdk1.6 through following code:
FileOutputStream fstrm = new FileOutputStream(f);
ObjectOutput ostrm = new ObjectOutputStream(fstrm);          ostrm.writeObject(textPane.getStyledDocument());
ostrm.flush();               but while reading the file through the following code the image is ok but the text is corrupted and showing some other mixed characters:
FileInputStream fin = new FileInputStream(f);
ObjectInputStream istrm = new ObjectInputStream(fin);
StyledDocument styledoc = (StyledDocument) istrm.readObject();im just confused now!!!!!!!!
plz help
best regards
tanvir

pls somebuddy help me on the problem
best regards
tanvir

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.

  • Lines around type and other type/text problems in Dreamweaver CS3

    Dear Dreamweaver forum:
    Good news/bad news,
    First the good news…
    My thanks to a forum member by the name of Mylenium. With Mylenium's advice I have improved my halo problem by including a black background when I save type in Illustrator CS3 as part of importing it into Dreamweaver CS3.
    However, the bad news, is that I’m still having type and text problems.
    Problem area 1
    Now, in Dreamweaver, I’m getting lines appearing around the type.
    I am dragging and dropping the .gif type file into a Dreamweaver Div Tag.
    How do I get rid of the lines around the type so that they do not show up in the Safari browser?
    (Please see below)
    Problem area 2
    I cannot drag and drop text from a Word .doc file into a Dreamweaver div tag.
    I also cannot copy and paste Word .doc text into a div tag.
    How do I include text on my webpage without having to manually type it in?
    (Please see below)
    Any help would be appreciated. Thanks! 
    From within Dreamweaver CS3, how do I place text? Dragging and droppign the file does not work.
    This is screenshot of what I see so far when I use Safari to test what I have made so far in Dreamweaver CS3.
    I get lines around type.........not usually a good thing.........How do I fix it?
    The way I created the portfolio type in IllustratorCS3 using the File > Save for Web and Devices. I then imported the resulting .gif file so that it was within my root folder within the Files panel within Dreamweaver CS3.
    Am I doing this right?

    Hi
    The problems you are experiencing with the image text, (why are you using image text, these days?) is probably cause by the image having a border when created in illustrator, or the image size being set incorrectly.
    As for the word text if you are using windows, see http://livedocs.adobe.com/en_US/Dreamweaver/9.0/help.html?content=WSc78c5058ca073340dcda91 10b1f693f21-7ce6.html.
    On the mac it is a little more complex, save your word doc as html, then apply the 'clean up word html files', (see - http://livedocs.adobe.com/en_US/Dreamweaver/9.0/help.html?content=WSc78c5058ca073340dcda91 10b1f693f21-7ef5.html) copy the relevant text and mark-up from the word html file, and paste into your html document in the required position.
    PZ
    www.pziecina.com

  • Workaround for the Fade/Appear blocky text problem in IE

    Just wanted to share with folks a workaround for the IE
    "blocky text" problem that you see when using Fade effects like the
    one used in this example:
    http://labs.adobe.com/technologies/spry/samples/data_region/DetailRegionEffectsSample.html
    It turns out if you set the 'background' CSS property on the
    element you are fading, that IE properly renders the text. So to
    fix the effects sample above, all you would have to do is modify
    this CSS rule in the file to place a background color on the
    description region to get things to look good in IE:
    #description {
    opacity: 0;
    filter: alpha(opacity=0);
    background: white;
    So if folks have been avoiding the use of effects because it
    makes things look terrible in IE, you now have a workaround.
    --== Kin ==--

    I was using spry's AppearFade effect to transition between
    "slides" in what equates to a viewstack that I created.
    Then I noticed that it would take bold text in IE and make it
    look all smudgy or blurry.
    Well, after working on it for a while, I got to thinking,
    "This problem is specific to text rendered in MicroSofts
    browser"... "Hmmm, I wonder".
    So, I tried using this style rule: [ font-family:"MS Sans
    Serif",Arial, Geneva, sans-serif; ].
    Lo and behold, feed the stupid MS browser an MS font and it
    does not blur the text.
    I just wanted to get this our there. Because someone might
    want to solve this in a way where they don't have to set a
    background color...

  • E6 Big Texting Problem

    Can anybody help me out with this problem?
    My E6 has developed a texting problem, whenever I send a text none of the text appears in the conversation speech bubble, just the date or time when it was sent and the character "0". Does anyone know why?
    Thanks
    Solved!
    Go to Solution.
    Attachments:
    Text.jpg ‏1560 KB

    Would suggest that you backup E6-00 using Nokia Suite, then reset device to "Out of box" state by keying in *#7370# followed by 12345 (default Nokia lock code unless altered by user). Perhaps restore contacts only and try out texting/conversations before restoring device any further.
    Happy to have helped forum in a small way with a Support Ratio = 37.0

  • Inserting text from one JTextpane to another

    How do i insert text from one jTextpane to another with the attributes i used in the first. Please help.

    i'm using a defaultstyleddocument. Also.....if u know
    how i can transfer this data through a
    DataOutputStream to another computer.Hi again,
    DefaultstyledDocument uses a tree-structure with classes in it, that implements the Element-Interface to hold the styles. It is very easy to get the plain text, but what you need to transfer a part of text from one JTextPane with DefaultStyledDocument in it to another with the same document-style in it, is a sequence of (string, AttributSet) - pairs, so you are able to insert them in the destination document by the insertString(...)-method.
    It is easy to get the Element by postion from the document and retrieve the Attributset from it that it uses in that position. I guess, an approach would be, to do the following:
    get the Attributset at the start of the text = AttributSet of the pair
    scan the document until the set changes
    extract the string from start to the position right before the set changes = string of the pair
    store the (String,AttributSet)-pair in a Vector
    do this in the same way, but this time the "start" will be the position of the start of the new Attributset that causes the end of the scan above.
    When this is done for the hole text, that is to be transferred, you have a Vector with the String-AttributSet-pairs that you can use to insert them in the other JTextPane by calling the
    insertString(...)-method with this values.
    Tell me, what you are thinking about that - I don't know another method for this and had to create a solution on the fly for you, so that is perhaps not the best way to do it.
    greetings Marsian

  • Aligning text in a JtextPane

    I am trying to display text in a JTextPane. I want to be able to change the background color, the foreground color and the border (color and width). Furthermore, I need multiple lines of text, and later I might want to change the font too. The text need not be editable. All this works ok with a JTextPane, except the alignment of the text. The text is always left-aligned. So the question is: what can I do to center the text in a JTextPane?
    Thanx in advance.

    Try somthing like this then
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    public class TestHTMLLabel {
    public static void main(String[] args) {
    JFrame frame= new JFrame("HTML Label");
    JLabel lbl = new JLabel("<html><p align=\"left\"><B>Thanx</B> for the reply, but I am really looking for a much simpler solution. Let me rephrase my question: I want to display a rectangular area on the screen that displays wrapped text within that rectangle. I also want to be able to change the colors (<font color=\"red\">foreground</font> and background) and the border (width, color and style). The text need not be editable<p></html> ");
    frame.getContentPane().add(lbl);
    frame.setSize(300,300);
    frame.show();
    Goodluck...

  • Nokia C3-00 texting problem.

    Hello everyone, this is my frist post on here. So i bought the nokia c3 and unlocked it from the vodafone network. I use my 02 sim now. I just discovered something that annoys me and need help getting rid of it.
    My problem is that after every text send the phone virbates letting me know that i have sent the text and my balance comes up. how do i change the settings so that this doesn't come up. Really annoying as i've just got a new number and sent out a mass text to everyone. The phone vibrated for like 2 minutes straight!!
    Any help greatly appreciated. Thank you.

    At the phone store where I bought the Nokia C3  they removed the Vodaphone  presets ( since I have  another provider ) and they also updated my phone with the latest software available ( see below ).
    But now I have a serious texting problem!
    If you type the Q you get an A , a=q , z=w  and w=z .
    Also after you typed something and you delete the text  and reopen the textbox again this word will reappear on a blue underscore?? Anyone any idea what's happened or had the same problem??
    The phone's update info:
    C3-00
    V04.45
    04-08-10
    RM-614
    Variant: 00.00
    Vitual variant: No Virt. Var.

  • Text Problems in Safari 4

    Just this morning I started to experience bad text rendering problems in Safari 4. I am seeing text that overlaps on other text, text that leaves a button and crosses over into the space next to it, text that is truncated on buttons, image alignment problems, and more. Typing in text boxes is a problem, too -- the cursor doesn't display at the point where text is actually being inserted, but several characters off.
    It doesn't affect every site -- Google and Netflix look OK, while Apple and Facebook are strongly affected to the point of being almost unusable. Firefox and Chrome on the same laptop are working fine. Other programs on the system, like TextEdit, are fine, too. I have tried changing the default font preferences in Safari, but while the text size changes on certain pages, the overlapping text problem isn't helped.
    I have screenshots of the issue -- how do I post them?
    Does anyone else see this issue? Many thanks for your opinions and advice?
    Safari Version 4.0.3 (6531.9)

    Where did you get 67 errors? http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fwww.totallybarbado s.com%2F shows the only error is the "pre" tag which are necessary hacks for formatting the "pre" tag. The other "warnings" are no different than checking apple.com http://jigsaw.w3.org/css-validator/validator?profile=css2&warning=2&uri=http://w ww.apple.com
    They also do not assign background-color to "every" css element. Why would you (to bloat CSS)? So, there is exactly "one" error which is well documented and is supported in CSS2.1 when released.
    The problem is that Safari does not adhere to white-space or "pre" tags (preformatted text). This has been an ongoing problem since it's incarnation. All other browsers (FireFox, Netscape, IE, Opera, Mozilla..etc) do. http://www.w3.org/TR/1998/REC-html40-19980424/struct/text.html#h-9.3.4
    edited: Sorry, had to edit as this forum software actually rendered the <"> tags (without quotes)

  • Weird texting problem

    I have a Z1s running 5.0.2 and I'm not a big texter.  I'm using the stock apps for texting and contacts.  I was trying to send a text to someone I had never texted before.  I brought up their contact page and pressed the little text icon and I got a texting screen except that it was covered by a menu that had options like 'add video', 'add picture' and a bunch of others that prevented me from actually being able to text.  The options did nothing and the back arrow also did nothing, so I was prevented from composing and sending a text.  I sent the text I needed to from my desktop using mighty text.  When I received a reply, I was prevented from reading it by the same menu which still did nothing.  That was yesterday.  Today, the menu was gone and I could read the return text.  For a while though, I was prevented from reading any other text I had received.  I would press on one and the first one I looked at came up instead.  Then that went away after a while and things seemed to have returned to 'normal'. I really don't understand what is going on with my phone.  I like the phone and I love the battery life, but this bit of weirdness and the fact that some apps that worked just fine on my N4, don't seem to work at all on the Z1s.  I have an app named Move that counts your steps during your day.  It worked just fine on my N4, but on the Z1s it's only counting maybe 1-3% of my steps.  It says I walked 89 steps yesterday and that is absurd.  I assume that the app uses the accellerometer to do its work.  I have another app that uses the gps for tracking and it's not registering anything even though the gps seems to be functioning.  And the phone doesn't have as good a connection during calls as my N4.  I get a lot of static and breaking up during calls that I never got on my N4.  99% of my calls are made and received at my home, so that is what I'm comparing.   Anyone have any clues as to what is going on here?  The update to lollipop was done through the pc connection.  Any additional updates have been done OTA.  I haven't rebooted in a while and I think I'll try that first. TIALT

    The texting problem has gone away for a while, so I can't take a screen shot.  I loaded the suggested messaging and google fit.  I don't like changing apps if what I had worked under lollipop on my N4 and now that I have the Z1s also running lollipop they don't.  It seems to me that Sony must have something to do with this problem.  Either the hardware or the software (os) is significantly different (inferior).  The gps tracking app I'm using is called Bubbler.  I tested it today and it only registered my location a handful of times instead of the every 5 or 10 minutes like it's supposed to.  To me this indicates that the gps is not functioning properly. The phone and the sim card are about a month old and it came as a micro sim. I don't mean to be a whiner, I'm just confused and disappointed that things are not functioning as I expected.  And on top of all that, the call quality is less than stellar. SorryLT

  • Problems with JTextPane line wrapping

    Hi to all.
    I'm using a code like this to make editable a figure that I paint with Java 2D. This JTextPane don't has a static size and for that, the text in it cannot be seen affected by the natural line wrap of the JTextPane component. The problem is that I have to set a maximun size for the JTextPane and I want to use the line wrap only when the width of the JTextPane be the maximun width. How can I do this?
    public class ExampleFrame extends JFrame {
        ExamplePane _panel;
        public ExampleFrame() {
            this.setSize(600, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            _panel = new ExamplePane();
            getContentPane().add(_panel);
            this.setVisible(true);
        public static void main(String[] args) {
            ExampleFrame example = new ExampleFrame();
        public class ExamplePane extends JPanel {
            public ExamplePane() {
                this.setBackground(Color.RED);
                this.setLayout(null);
                this.add(new ExampleText());
        public class ExampleText extends JTextPane implements ComponentListener, DocumentListener,
                KeyListener {
            public ExampleText() {
                StyledDocument doc = this.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
                StyleConstants.setAlignment(standard, StyleConstants.ALIGN_RIGHT);
                doc.setParagraphAttributes(0, 0, standard, true);
                this.setText("Example");
                this.setLocation(300, 300);
                this.setSize(getPreferredSize());
                this.addComponentListener(this);
                getDocument().addDocumentListener(this);
                this.addKeyListener(this);
            public void componentResized(ComponentEvent e) {
            public void componentMoved(ComponentEvent e) {
            public void componentShown(ComponentEvent e) {
            public void componentHidden(ComponentEvent e) {
            public void insertUpdate(DocumentEvent e) {
                Dimension d = getPreferredSize();
                d.width += 10;
                setSize(d);
            public void removeUpdate(DocumentEvent e) {
            public void changedUpdate(DocumentEvent e) {
            public void keyTyped(KeyEvent e) {
            public void keyPressed(KeyEvent e) {
            public void keyReleased(KeyEvent e) {
    }Thanks for read.

    I'm working hard about that and I can't find the perfect implementation of this. This is exactly what I want to do:
    1. I have a Ellipse2D element painted into a JPanel.
    2. This ellipse is painted like a circle.
    3. Into the circle there's a text area, that user use to name the cicle.
    4. The text area is a JTextPane.
    5. When the user insert a text area, it can increase it size, but it can't be bigger than the circle that it contains.
    6. There is a maximun and a minimun size for the circle.
    7. When the user write into de JTextPane, it grows until arriving at the limit.
    8. When the JTextPane has the width size limit, if the user writes more text into it, the JTextPane write it into another line.
    9. The size of the JTextPane has to be the optimun size, it cannot have empty rows or empty lines.
    This code does all this except 9, cause if the user remove some text of the text area, the form of the JTextPane changes to a incorrect size.
    public class ExampleFrame extends JFrame {
        ExamplePane _panel;
        public ExampleFrame() {
            this.setSize(600, 600);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            _panel = new ExamplePane();
            getContentPane().add(_panel);
            this.setVisible(true);
        public static void main(String[] args) {
            ExampleFrame example = new ExampleFrame();
        public class ExamplePane extends JPanel {
            public ExamplePane() {
                this.setBackground(Color.RED);
                this.setLayout(null);
                this.add(new ExampleText());
        public class ExampleText extends JTextPane implements ComponentListener, DocumentListener,
                KeyListener {
            public ExampleText() {
                StyledDocument doc = this.getStyledDocument();
                MutableAttributeSet standard = new SimpleAttributeSet();
                StyleConstants.setAlignment(standard, StyleConstants.ALIGN_CENTER);
                doc.setParagraphAttributes(0, 0, standard, true);
                this.setText("Example");
                this.setLocation(300, 300);
                this.setSize(getPreferredSize());
                //If it has the maximun width and the maximun height, the user cannot
                //write into the JTextPane
                /*AbstractDocument abstractDoc;
                if (doc instanceof AbstractDocument) {
                abstractDoc = (AbstractDocument) doc;
                abstractDoc.setDocumentFilter(new DocumentSizeFilter(this, 15));
                this.addComponentListener(this);
                getDocument().addDocumentListener(this);
                this.addKeyListener(this);
            public void componentResized(ComponentEvent e) {
            public void componentMoved(ComponentEvent e) {
            public void componentShown(ComponentEvent e) {
            public void componentHidden(ComponentEvent e) {
            public void insertUpdate(DocumentEvent e) {
                Runnable doRun = new Runnable() {
                    public void run() {
                        int MAX_WIDTH = 200;
                        Dimension size = getSize();
                        Dimension preferred = getPreferredSize();
                        if (size.width < MAX_WIDTH) {
                            size.width += 10;
                        } else {
                            size.height = preferred.height;
                        setSize(size);
                SwingUtilities.invokeLater(doRun);
            public void removeUpdate(DocumentEvent e) {
                this.setSize(this.getPreferredSize());
            public void changedUpdate(DocumentEvent e) {
            public void keyTyped(KeyEvent e) {
            public void keyPressed(KeyEvent e) {
            public void keyReleased(KeyEvent e) {
    }I know that the problem is into the removeUpdate method, but I have to set to the JTextPane, allways the optimun size, how can I do this?
    Thanks to all.
    Edited by: Daniel.GB on 06-jun-2008 18:32

  • Copy and paste problem  in JTextPane????

    Hello,
    Just I am tring copy and paste the following text in JTextPane (jdk1.3):
    "that�s right" I got "that[]s right"
    How to eleminate []???
    -redlotus

    Hello,
    The problem has been solved by over writing the � font.properties � file in jre/lib/� .
    The changes given as follows:
    # Exclusion Range info.
    # exclusion.dialog.0=0500-20ab,20ad-ffff
    # exclusion.dialoginput.0=0500-20ab,20ad-ffff
    # exclusion.serif.0=0500-20ab,20ad-ffff
    # exclusion.sansserif.0=0500-20ab,20ad-ffff
    # exclusion.monospaced.0=0500-20ab,20ad-ffff
    That is, we comment the lines having Red foreground color.

  • A problem with JTextPane

    I'm making a simple java IDE with a JTextPane. I can get syntax hightlighting to work, but I'm having some strange problems. If you type too fast, the caret jumps to the beginning of the pane and starts putting your text there. I'm also getting a NoSuchElementException with a LinkedList that I use, but have no idea why. The codes kinda long, so I figured it would probably be better to link you to a zip file of my files so you can open them in whatever IDE you prefer instead of having to read them off this site. Here's the URL http://www.freewebs.com/dustpyle_x2/misc/jide.zip
    The MajorGradeDTP class is the driver.
    Any help would be greatly appreciated!

    Please help....No one really likes to download files. If it is to big to post here, then your example is not simple enough.
    Narrow down your example and question and someone here might be willing to look at it.

  • Cannot UN-bold text in a JTextPane

    This is a strange one. I copied the code from my ap into the runable sample below. I can select a portion of text and then click the "Bold" button and the selected text gets turned to bold. Now if I select the bold text and click the bold button again, nothing happens. HOWEVER, if I select ANY portion of the bold text except for the very last character then I can unbold it.
    If I ever select the very last character of a bolded section it will not unbold the section. So I am always left with one character that I can not unbold.
    Any ideas what I'm doing wrong. (The relevant code from my real ap is what is inside the boldButton ActionListener)
    BTW: I'm a relative newbie to Java.
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.border.*;
    import java.awt.*;              //for layout managers and more
    import java.awt.event.*;        //for action events
    public class Bolder extends JPanel
        private String newline = System.getProperty("line.separator");
        private JTextPane textPane;
        private JLabel label;
        private JPanel parent;
        private JComponent dragging = null;
        private int mOffsetX, mOffsetY;
        public Bolder() {
            setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
            JToolBar toolBar = buildToolbar();
            add(toolBar);
            parent = new JPanel();
            add(parent);
            parent.setBackground( Color.white);
            parent.setPreferredSize(new Dimension(640, 480));
            // Create a text pane.
            textPane = createTextPane();
            textPane.setBounds(0, 0, 100, 100);
            Border myBorder = BorderFactory.createLineBorder( Color.red );
            textPane.setBorder(myBorder);
            parent.add(textPane);
        private JTextPane createTextPane() {
            String[] initString =
                { "This is some sample text ",
                    "including some bold ",
                    "That can be used for testing purposes."+newline+"If you bold a piece of text"+
                    " then it cannot be unbolded entirely. All but the last character can be unbolded."+newline+
                    "A most peculiar phenomenon."
            String[] initStyles =
                    { "regular", "bold", "regular" };
            JTextPane textPane = new JTextPane();
            StyledDocument doc = textPane.getStyledDocument();
            addStylesToDocument(doc);
            try {
                for (int i=0; i < initString.length; i++) {
                    doc.insertString(doc.getLength(), initString,
    doc.getStyle(initStyles[i]));
    catch (BadLocationException ble) {
    System.err.println("Couldn't insert initial text into text pane.");
    return textPane;
    protected void addStylesToDocument(StyledDocument doc) {
    // Initialize some styles.
    Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    Style regular = doc.addStyle("regular", def);
    StyleConstants.setFontFamily(def, "SansSerif");
    Style s = doc.addStyle("italic", regular);
    StyleConstants.setItalic(s, true);
    s = doc.addStyle("bold", regular);
    StyleConstants.setBold(s, true);
    s = doc.addStyle("small", regular);
    StyleConstants.setFontSize(s, 10);
    s = doc.addStyle("large", regular);
    StyleConstants.setFontSize(s, 16);
    private JToolBar buildToolbar() {
    JToolBar toolBar = new JToolBar();
    toolBar.setRollover( true );
    toolBar.setFloatable( false );
    JButton boldButton = new JButton("Bold");
    boldButton.addActionListener( new ActionListener() {
    public void actionPerformed( ActionEvent e ) {
    AttributeSet current = textPane.getCharacterAttributes();
    if (current==null) {
    // if no currently selected text, apply bold to anything typed in the future
    // at this location.
    current = textPane.getInputAttributes();
    MutableAttributeSet attr = new SimpleAttributeSet();
    boolean bold = false;
    if (current.getAttribute(StyleConstants.Bold)!=null) {
    bold = (current.getAttribute(StyleConstants.Bold).toString()=="true") ? true : false;
    if (bold) {
    StyleConstants.setBold(attr, false);
    } else {
    StyleConstants.setBold(attr,true);
    textPane.setCharacterAttributes(attr, false);
    toolBar.add( boldButton );
    return toolBar;
    private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("Bolder");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create and set up the content pane.
    JComponent newContentPane = new Bolder();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    Here's a work around that ALMOST works: surrounding the line
    bold = (current.getAttribute(StyleConstants.Bold).toString()=="true") ? true : false;Where I decide if the text was previous bolded or not, I add a call to textRegion.setSelectionEnd(...); to set the end of the selection to one character less, then get the attributes and then set the end of the selection back to the original position.
    The only problem is, it doesn't work if you select only one character to bold or unbold.
    --gary                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Problem using JTextPane with large styled docs

    I have an environment where we need to parse out large (5MB) log files, and I'm displaying them with colorized attributes such as logging level, timestamp, etc. The files are read in once and never changed, only displayed - the text is not editable, so we don't care about future updates to the doc (only highlighting text for find/copy). However we do need the entire document 'available' after load in order to do string searches and certain operations linked to the entry a piece of text is in.
    Parsing and building the styled document are relatively fast operations (a couple seconds), but when I set the document on the JTextPanel (which is inside a JScrollBar), it can take an enormous amount of time to display, and sometimes eats up every resource on the machine, eventually stoping dead without displaying at all (out of memory maybe?).
    I've read similar posts on the forum, but no one has provided a clear-cut solution to this problem. Is there a simple way to make my document display quickly? Alternatively, is there another way to implement this without using JTextPane?
    Any help is much appreciated.
    Thanks,
    lex

    In the past I tried to optimize ParagraphView and SectionView of the kit. Don't know whether it will help in your case. Hope so.
    import javax.swing.text.*;
    import java.awt.Rectangle;
    import javax.swing.SizeRequirements;
    import java.awt.Shape;
    public class OptimizedParagraphView extends ParagraphView {
        public OptimizedParagraphView(Element elem) {
            super(elem);
        protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
            //optimized
            int preferred = 0;
            int n = getViewCount();
            for (int i = 0; i < n; i++) {
                View v = getView(i);
                spans[i] = (int) v.getPreferredSpan(axis);
                offsets=preferred;
    preferred += spans[i];
    protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
    //optimized
    int n = getViewCount();
    for (int i = 0; i < n; i++) {
    View v = getView(i);
    int min = (int) v.getMinimumSpan(axis);
    offsets[i] = 0;
    spans[i] = Math.max(min, targetSpan);
    public int getResizeWeight(int axis) {
    //optimized
    return 0;
    public float getAlignment(int axis) {
    //opimized
    return 0;
    protected View createRow() {
    //optimized
    return new OptimizedRow(getElement());
    class OptimizedRow extends BoxView {
    SizeRequirements mimorRequirements;
    OptimizedRow(Element elem) {
    super(elem, View.X_AXIS);
    protected void loadChildren(ViewFactory f) {
    public AttributeSet getAttributes() {
    View p = getParent();
    return (p != null) ? p.getAttributes() : getElement().getAttributes();
    public float getAlignment(int axis) {
    if (axis == View.X_AXIS) {
    switch (StyleConstants.getAlignment(getAttributes())) {
    case StyleConstants.ALIGN_LEFT:
    return 0;
    case StyleConstants.ALIGN_RIGHT:
    return 1;
    case StyleConstants.ALIGN_CENTER:
    case StyleConstants.ALIGN_JUSTIFIED:
    return 0.5f;
    return 0;
    public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException {
    Rectangle r = a.getBounds();
    View v = getViewAtPosition(pos, r);
    if ((v != null) && (!v.getElement().isLeaf())) {
    // Don't adjust the height if the view represents a branch.
    return super.modelToView(pos, a, b);
    r = a.getBounds();
    int height = r.height;
    int y = r.y;
    Shape loc = super.modelToView(pos, a, b);
    r = loc.getBounds();
    r.height = height;
    r.y = y;
    return r;
    public int getStartOffset() {
    int offs = Integer.MAX_VALUE;
    int n = getViewCount();
    for (int i = 0; i < n; i++) {
    View v = getView(i);
    offs = Math.min(offs, v.getStartOffset());
    return offs;
    public int getEndOffset() {
    int offs = 0;
    int n = getViewCount();
    for (int i = 0; i < n; i++) {
    View v = getView(i);
    offs = Math.max(offs, v.getEndOffset());
    return offs;
    protected void layoutMinorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
    baselineLayout(targetSpan, axis, offsets, spans);
    protected SizeRequirements calculateMinorAxisRequirements(int axis,
    SizeRequirements r) {
    mimorRequirements= baselineRequirements(axis, r);
    return mimorRequirements;
    protected SizeRequirements baselineRequirements(int axis, SizeRequirements r) {
    if (r == null) {
    r = new SizeRequirements();
    int n = getViewCount();
    // loop through all children calculating the max of all their ascents and
    // descents at minimum, preferred, and maximum sizes
    int span=0;
    for (int i = 0; i < n; i++) {
    View v = getView(i);
    // find the maximum of the preferred ascents and descents
    span = Math.max((int)v.getPreferredSpan(axis),span);
    r.preferred = span;
    r.maximum=span;
    r.minimum=span;
    return r;
    protected int getViewIndexAtPosition(int pos) {
    // This is expensive, but are views are not necessarily layed
    // out in model order.
    if(pos < getStartOffset() || pos >= getEndOffset())
    return -1;
    for(int counter = getViewCount() - 1; counter >= 0; counter--) {
    View v = getView(counter);
    if(pos >= v.getStartOffset() &&
    pos < v.getEndOffset()) {
    return counter;
    return -1;
    protected short getLeftInset() {
    View parentView;
    int adjustment = 0;
    if ((parentView = getParent()) != null) { //use firstLineIdent for the first row
    if (this == parentView.getView(0)) {
    adjustment = firstLineIndent;
    return (short)(super.getLeftInset() + adjustment);
    protected short getBottomInset() {
    float lineSpacing=StyleConstants.getLineSpacing(getAttributes());
    return (short)(super.getBottomInset() + mimorRequirements.preferred * lineSpacing);
    protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
    //optimized
    int preferred = 0;
    int n = getViewCount();
    for (int i = 0; i < n; i++) {
    View v = getView(i);
    spans[i] = (int) v.getPreferredSpan(axis);
    offsets[i]=preferred;
    preferred += spans[i];
    public int getResizeWeight(int axis) {
    //optimized
    return 0;
    import javax.swing.text.*;
    public class OptimizedSectionView extends BoxView {
    public OptimizedSectionView(Element elem) {
    super(elem,View.Y_AXIS);
    protected void layoutMajorAxis(int targetSpan, int axis, int[] offsets, int[] spans) {
    //optimized
    int preferred = 0;
    int n = getViewCount();
    for (int i = 0; i < n; i++) {
    View v = getView(i);
    spans[i] = (int) v.getPreferredSpan(axis);
    offsets[i]=preferred;
    preferred += spans[i];
    public int getResizeWeight(int axis) {
    //optimized
    return 0;
    public float getAlignment(int axis) {
    //opimized
    return 0;
    class MyViewFactory implements ViewFactory {
    * Creates view for specified element.
    * @param elem Element parent element
    * @return View created view instance.
    public View create(Element elem) {
    String kind = elem.getName();
    if (kind != null) {
    if (kind.equals(AbstractDocument.ContentElementName)) {
    return new LabelView(elem);
    else if (kind.equals(AbstractDocument.ParagraphElementName)) {
    return new OptimizedParagraphView(elem);
    // return new ParagraphView(elem);
    else if (kind.equals(AbstractDocument.SectionElementName)) {
    return new OptimizedSectionView(elem);
    // return new BoxView(elem, View.Y_AXIS);
    else if (kind.equals(StyleConstants.ComponentElementName)) {
    return new ComponentView(elem);
    else if (kind.equals(StyleConstants.IconElementName)) {
    return new IconView(elem);
    // default to text display
    return new LabelView(elem);
    regards,
    Stas

Maybe you are looking for