Results 1 to 2 of 2
  1. #1
    Jeff Smith is offline Member
    Join Date
    Jul 2009
    Posts
    1
    Rep Power
    0

    Default Print multi-colored characters in a sentence

    Hello All,

    I just taught Java to myself this past week, and so not surprisingly, I'm stuck with this program.

    Basically I want to print out two sequences in separate lines in a JTextPane (I realized JTextArea is incapable of multi-colored edits). For each position in the sequences, if the two sequences have the same character, I want to print the character in black. Otherwise, if they differ at a particular spot, I want to print the two different letters of the two sequences in red. Here is my code for that:

    for( int posBY = 0; posBY < byOutput.length(); posBY++ )
    {
    SimpleAttributeSet attrs = new SimpleAttributeSet();

    if( byOutput.charAt( posBY ) == rmOutput.charAt( posBY ))
    {
    outputArea.setText(outputArea.getText()+byOutput.c harAt (posBY)+"");
    StyledDocument sdoc = outputArea.getStyledDocument();
    StyleConstants.setForeground( attrs, Color.BLACK);
    sdoc.setCharacterAttributes( byOutput.charAt( posBY ), 1, attrs, true);
    }
    else
    {
    outputArea.setText(outputArea.getText()+byOutput.c harAt (posBY)+"");
    StyledDocument sdoc = outputArea.getStyledDocument();
    StyleConstants.setForeground( attrs, Color.RED);
    sdoc.setCharacterAttributes( byOutput.charAt( posBY ), 1, attrs, true);
    }
    }

    But this doesn't work, because my output is all in black characters.

    Do you guys know what I'm doing wrong?

    Thanks for the help! :)

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    You need to make up the styles and add them to the styledDocument and use/refer to them in applying them to text at various positions in the document.
    For an example see the section An Example of Using a Text Pane on How to Use Editor Panes and Text Panes.

Similar Threads

  1. enter a string sentence
    By amorosa19 in forum New To Java
    Replies: 13
    Last Post: 09-06-2013, 11:34 AM
  2. SWT List w/ colored lines?
    By p!lle in forum SWT / JFace
    Replies: 1
    Last Post: 03-23-2009, 04:23 PM
  3. Replies: 2
    Last Post: 08-10-2007, 01:36 AM
  4. How to extract info from a sentence
    By luisarca in forum XML
    Replies: 1
    Last Post: 06-07-2007, 06:43 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •