1 Reply Latest reply on May 13, 2011 5:22 AM by StanislavL

    AttributedString question

      I am having trouble understanding the documentation for java.text.AttributedString.

      I would like to get the indices of a run that contains an AttributedCharacterIterator.Attribute.

      So suppose I have an attribute whose name is "fred" and whose value is "flintstone" and I want to apply it to the AttributedString's 0th through 4th character, inclusive.

      If I am iterating through a 10-character AttributedString, then when I reach the fifth character, the return value of getRunStart(myFredFlintstoneAttribute) suddenly returns 5.

      I have a suspicion this has to do with the extremely odd and opaque documentation of AttributedCharacterIterator, which is the type of iterator that an AttributedString returns.

      I've attached my code in case it helps (this is a JUnit test):

      final AttributedString s = new AttributedString("SQ3R9FFFFF");
      final Attribute fred = new Attribute("fred") {};
      s.addAttribute(fred, new Annotation("flintstone"), 0, 5);
      final AttributedCharacterIterator iterator = s.getIterator();

      for (char c = iterator.first(); c != DONE; c = iterator.next()) {
      System.out.println("Character: " + c);
      System.out.println("Character index: " + iterator.getIndex());
      System.out.println("Attributes: " + iterator.getAttributes());
      System.out.println("Start for fred: " + iterator.getRunStart(fred));
      System.out.println("Limit for fred: " + iterator.getRunLimit(fred));
      System.out.println("General run start: " + iterator.getRunStart());
      System.out.println("General run start: " + iterator.getRunLimit());

      The output is exceedingly odd (to me). Specifically, when iteration reaches, for example, the 7th character, you get this:
      Character: F
      Character index: 6
      Attributes: {}
      Start for fred: 5
      Limit for fred: 10
      General run start: 5
      General run start: 10

      Why is the start for the "fred" run indicated as being 5?

        • 1. Re: AttributedString question
          from source code
               * Adds an attribute to a subrange of the string.
               * @param attribute the attribute key
               * @param value The value of the attribute. May be null.
               * @param beginIndex Index of the first character of the range.
               * @param endIndex Index of the character following the last character of the range.
              public void addAttribute(Attribute attribute, Object value,
                      int beginIndex, int endIndex) {
          As you can see if you set endIndex to 5 so next fragment starts from 5.