tags:

views:

48

answers:

2

Hello all,

I have a problem with a part of a project i am working on. I want to display some emoticons using Java Swing, however it won't allow me to display consecutive identical styles:

This works fine: Smile Sad Grin

This doesn't work: Smile Smile Smile

I am using Styled Document and have little experience with it. The code is as follows:

       public static void addStylesToDocument(StyledDocument doc) {
        //Initialize some styles.
        ImageIcon laugh = new ImageIcon("laugh.gif");
        ImageIcon sad  = new ImageIcon("sad.gif");
        ImageIcon tongue = new ImageIcon("tongue.gif");
        ImageIcon smile = new ImageIcon("smile.gif");
        ImageIcon cry = new ImageIcon("cry.gif");

        Style def = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);

        Style regular = doc.addStyle("regular", def);
        StyleConstants.setFontFamily(def, "SansSerif");

        Style s = doc.addStyle("laugh", def);
        StyleConstants.setIcon(s, laugh);

        Style sads = doc.addStyle("sad", regular);
        StyleConstants.setIcon(sads,sad);


        s = doc.addStyle("tongue", regular);
        StyleConstants.setIcon(s,tongue);


        s = doc.addStyle("smile", regular);
        StyleConstants.setIcon(s,smile);


        s = doc.addStyle("cry", regular);
        StyleConstants.setIcon(s,cry);
    }

^ adding styles to my document

        for (i=0;i<typeOfText.size();i++){
            System.out.println(parsedText.get(i) + " " +  typeOfText.get(i) + " " + i + " " + doc.getLength());
            doc.insertString(doc.getLength(),parsedText.get(i),doc.getStyle(typeOfText.get(i)));
        }   

^ applying the styles to the parsed Text.

So my question is: does Styled Document have a certain property so that when i have same styles one after another it won't display them correctly?

EDIT: Each text is broken down with String Tokenizer, i get it to parse properly, and apply the appropriate style.

+1  A: 

Styles will be collapsed if there are multiple styles over consecutive runs of text. That is, multiple runs of text with the same style will be merged into one run of text. It sounds like you are displaying an image based just on the style. You will get multiple images output if you output an image for the number of characters within the given style rather than just the presence of a style.

Alternatively, instead of having a distinct style for each emoticon, have a general "emoticon" style, and render an appropriate image based on the text. E.g. :-) styled with emoticon will render a smiley. And :-):-) will render two smileys. By doing this, you maintain a meaningful relation between the document content and what is presented.

mdma
+1  A: 

Another option might be to use the insertIcon() method of JTextPane.

camickr