Java Code Examples for java.text.AttributedString#getIterator()

The following examples show how to use java.text.AttributedString#getIterator() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AttrStringUtils.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Draws the attributed string at <code>(textX, textY)</code>, rotated by 
 * the specified angle about <code>(rotateX, rotateY)</code>.
 * 
 * @param text  the attributed string (<code>null</code> not permitted).
 * @param g2  the graphics output target.
 * @param textX  the x-coordinate for the text.
 * @param textY  the y-coordinate for the text.
 * @param angle  the rotation angle (in radians).
 * @param rotateX  the x-coordinate for the rotation point.
 * @param rotateY  the y-coordinate for the rotation point.
 * 
 * @since 1.0.16
 */
public static void drawRotatedString(AttributedString text, Graphics2D g2, 
        float textX, float textY, double angle, float rotateX, 
        float rotateY) {
    ParamChecks.nullNotPermitted(text, "text");

    AffineTransform saved = g2.getTransform();
    AffineTransform rotate = AffineTransform.getRotateInstance(angle, 
            rotateX, rotateY);
    g2.transform(rotate);
    TextLayout tl = new TextLayout(text.getIterator(),
                g2.getFontRenderContext());
    tl.draw(g2, textX, textY);
    
    g2.setTransform(saved);        
}
 
Example 2
Source File: AttrStringUtils.java    From openstock with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Draws the attributed string at <code>(textX, textY)</code>, rotated by 
 * the specified angle about <code>(rotateX, rotateY)</code>.
 * 
 * @param text  the attributed string (<code>null</code> not permitted).
 * @param g2  the graphics output target.
 * @param textX  the x-coordinate for the text.
 * @param textY  the y-coordinate for the text.
 * @param angle  the rotation angle (in radians).
 * @param rotateX  the x-coordinate for the rotation point.
 * @param rotateY  the y-coordinate for the rotation point.
 * 
 * @since 1.0.16
 */
public static void drawRotatedString(AttributedString text, Graphics2D g2, 
        float textX, float textY, double angle, float rotateX, 
        float rotateY) {
    ParamChecks.nullNotPermitted(text, "text");

    AffineTransform saved = g2.getTransform();
    AffineTransform rotate = AffineTransform.getRotateInstance(angle, 
            rotateX, rotateY);
    g2.transform(rotate);
    TextLayout tl = new TextLayout(text.getIterator(),
                g2.getFontRenderContext());
    tl.draw(g2, textX, textY);
    
    g2.setTransform(saved);        
}
 
Example 3
Source File: JMultilineLabel.java    From Spark with Apache License 2.0 6 votes vote down vote up
private Dimension paintOrGetSize(Graphics2D g, int width) {
    Insets insets = getInsets();
    width -= insets.left + insets.right + margin.left + margin.right;
    float w = insets.left + insets.right + margin.left + margin.right;
    float x = insets.left + margin.left, y = insets.top + margin.top;
    if (width > 0 && text != null && text.length() > 0) {
        AttributedString as = new AttributedString(getText());
        as.addAttribute(TextAttribute.FONT, getFont());
        AttributedCharacterIterator aci = as.getIterator();
        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
        float max = 0;
        while (lbm.getPosition() < aci.getEndIndex()) {
            TextLayout textLayout = lbm.nextLayout(width);
            if (g != null && isJustified() && textLayout.getVisibleAdvance() > 0.80 * width)
                textLayout = textLayout.getJustifiedLayout(width);
            if (g != null)
                textLayout.draw(g, x, y + textLayout.getAscent());
            y += textLayout.getDescent() + textLayout.getLeading() + textLayout.getAscent();
            max = Math.max(max, textLayout.getVisibleAdvance());
        }
        w += max;
    }
    return new Dimension((int)Math.ceil(w), (int)Math.ceil(y) + insets.bottom + margin.bottom);
}
 
Example 4
Source File: TextUtils.java    From orson-charts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Draws the attributed string at {@code (textX, textY)}, rotated by 
 * the specified angle about {@code (rotateX, rotateY)}.
 * 
 * @param text  the attributed string ({@code null} not permitted).
 * @param g2  the graphics output target ({@code null} not permitted).
 * @param textX  the x-coordinate for the text alignment point.
 * @param textY  the y-coordinate for the text alignment point.
 * @param angle  the rotation angle (in radians).
 * @param rotateX  the x-coordinate for the rotation point.
 * @param rotateY  the y-coordinate for the rotation point.
 * 
 * @return The text bounds (never {@code null}).
 * 
 * @since 1.2
 */
public static Shape drawRotatedString(AttributedString text, Graphics2D g2, 
        float textX, float textY, double angle, float rotateX, 
        float rotateY) {
    
    Args.nullNotPermitted(text, "text");
    AffineTransform saved = g2.getTransform();
    AffineTransform rotate = AffineTransform.getRotateInstance(angle, 
            rotateX, rotateY);
    g2.transform(rotate);
    TextLayout tl = new TextLayout(text.getIterator(),
                g2.getFontRenderContext());
    Rectangle2D rect = tl.getBounds();
    tl.draw(g2, textX, textY);
    g2.setTransform(saved);
    return rotate.createTransformedShape(rect);
}
 
Example 5
Source File: DesenhadorDeTexto.java    From brModelo with GNU General Public License v3.0 6 votes vote down vote up
private LineBreakMeasurer[] getLineBreakMeasurers(Graphics2D g) {
    if (lbmTexto == null && (Texto != null && !Texto.equals(""))) {
        lbmTexto = new LineBreakMeasurer[Textos.length];
        for (int i = 0; i < lbmTexto.length; i++) {
            String tmp = Textos[i].isEmpty()? " " : Textos[i];
            AttributedString attribString = new AttributedString(tmp);
            attribString.addAttribute(TextAttribute.FONT, getFont());
            //attribString.addAttribute(TextAttribute.FONT, getFont());
            AttributedCharacterIterator attribCharIterator = attribString.getIterator();
            //FontRenderContext frc = new FontRenderContext(null, true, false);
            FontRenderContext frc = g.getFontRenderContext();
            lbmTexto[i] = new LineBreakMeasurer(attribCharIterator, frc);
        }
    }
    return lbmTexto;
}
 
Example 6
Source File: Axis.java    From buffer_bci with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets the attributed label for the axis and sends an 
 * {@link AxisChangeEvent} to all registered listeners.
 * 
 * @param label  the label ({@code null} permitted).
 * 
 * @since 1.0.16
 */
public void setAttributedLabel(AttributedString label) {
    if (label != null) {
        this.attributedLabel = new AttributedString(label.getIterator());
    } else {
        this.attributedLabel = null;
    }
    fireChangeEvent();
}
 
Example 7
Source File: TitleFrame.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
static void drawCardName(BufferedImage cardImage, IRenderableCard cardDef) {
    String plainName = cardDef.getName();
    if (!plainName.isEmpty()) {
        //Add space to end of name to enable .end character ligatures
        AttributedString cardName = new AttributedString(plainName + ' ');
        Graphics2D g2d = cardImage.createGraphics();
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
        if (cardDef.isToken()) {
            g2d.setColor(Color.getHSBColor(54, 45, 100));
            cardName.addAttribute(TextAttribute.FONT, cardNameTokenFont);
        } else {
            g2d.setColor(Color.BLACK);
            cardName.addAttribute(TextAttribute.FONT, cardNameFont);
        }
        TextLayout metrics = new TextLayout(cardName.getIterator(), g2d.getFontRenderContext()); //to allow calculation of Ascent + length
        int xPos = 30;
        int yPos = 33;
        if (cardDef.isToken()) {
            xPos = (int) (cardImage.getWidth() / 2 - metrics.getBounds().getWidth() / 2);
            yPos = 27;
        } else if (cardDef.isPlaneswalker()) {
            yPos = 25;
        }
        g2d.drawString(cardName.getIterator(), xPos, yPos + metrics.getAscent());
        g2d.dispose();
    }
}
 
Example 8
Source File: AttributedStringUtilities.java    From ccu-historian with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Tests two attributed strings for equality.
 * 
 * @param s1  string 1 (<code>null</code> permitted).
 * @param s2  string 2 (<code>null</code> permitted).
 * 
 * @return <code>true</code> if <code>s1</code> and <code>s2</code> are
 *         equal or both <code>null</code>, and <code>false</code> 
 *         otherwise.
 */
public static boolean equal(AttributedString s1, AttributedString s2) {
    if (s1 == null) {
        return (s2 == null);
    }
    if (s2 == null) {
        return false;
    }
    AttributedCharacterIterator it1 = s1.getIterator();
    AttributedCharacterIterator it2 = s2.getIterator();
    char c1 = it1.first();
    char c2 = it2.first();
    int start = 0;
    while (c1 != CharacterIterator.DONE) {
        int limit1 = it1.getRunLimit();
        int limit2 = it2.getRunLimit();
        if (limit1 != limit2) {
            return false;
        }
        // if maps aren't equivalent, return false
        Map m1 = it1.getAttributes();
        Map m2 = it2.getAttributes();
        if (!m1.equals(m2)) {
            return false;
        }
        // now check characters in the run are the same
        for (int i = start; i < limit1; i++) {
            if (c1 != c2) {
                return false;
            }
            c1 = it1.next();
            c2 = it2.next();
        }
        start = limit1;
    }
    return c2 == CharacterIterator.DONE;
}
 
Example 9
Source File: SimpleColoredComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private TextLayout createTextLayout(String text, Font basefont, FontRenderContext fontRenderContext) {
  if (StringUtil.isEmpty(text)) return null;
  AttributedString string = new AttributedString(text);
  int start = 0;
  int end = text.length();
  AttributedCharacterIterator it = string.getIterator(new AttributedCharacterIterator.Attribute[0], start, end);
  Font currentFont = basefont;
  int currentIndex = start;
  for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
    Font font = basefont;
    if (!font.canDisplay(c)) {
      for (SuitableFontProvider provider : SuitableFontProvider.EP_NAME.getExtensions()) {
        font = provider.getFontAbleToDisplay(c, basefont.getSize(), basefont.getStyle(), basefont.getFamily());
        if (font != null) break;
      }
    }
    int i = it.getIndex();
    if (!Comparing.equal(currentFont, font)) {
      if (i > currentIndex) {
        string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, i);
      }
      currentFont = font;
      currentIndex = i;
    }
  }
  if (currentIndex < end) {
    string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, end);
  }
  return new TextLayout(string.getIterator(), fontRenderContext);
}
 
Example 10
Source File: BidiEmbeddingTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
static void test2() {
    String target = "BACK WARDS";
    String str = "If this text is >" + target + "< the test passed.";
    int length = str.length();
    int start = str.indexOf(target);
    int limit = start + target.length();

    System.out.println("start: " + start + " limit: " + limit);

    AttributedString astr = new AttributedString(str);
    astr.addAttribute(TextAttribute.RUN_DIRECTION, TextAttribute.RUN_DIRECTION_RTL);

    astr.addAttribute(TextAttribute.BIDI_EMBEDDING,
                     new Integer(-3),
                     start,
                     limit);

    Bidi bidi = new Bidi(astr.getIterator());

    for (int i = 0; i < bidi.getRunCount(); ++i) {
        System.out.println("run " + i +
                           " from " + bidi.getRunStart(i) +
                           " to " + bidi.getRunLimit(i) +
                           " at level " + bidi.getRunLevel(i));
    }

    System.out.println(bidi + "\n");

    if (bidi.getRunCount() != 6) { // runs of spaces and angles at embedding bound,s and final period, each get level 1
        throw new Error("Bidi embedding processing failed");
    } else {
        System.out.println("test2() passed.\n");
    }
}
 
Example 11
Source File: getRunStartLimitTest.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        String text = "Hello world";
        AttributedString as = new AttributedString(text);

        // add non-Annotation attributes
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_LIGHT,
                        0,
                        3);
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_BOLD,
                        3,
                        5);
        as.addAttribute(TextAttribute.WEIGHT,
                        TextAttribute.WEIGHT_EXTRABOLD,
                        5,
                        text.length());

        // add Annotation attributes
        as.addAttribute(TextAttribute.WIDTH,
                        new Annotation(TextAttribute.WIDTH_EXTENDED),
                        0,
                        3);
        as.addAttribute(TextAttribute.WIDTH,
                        new Annotation(TextAttribute.WIDTH_CONDENSED),
                        3,
                        4);

        AttributedCharacterIterator aci = as.getIterator(null, 2, 4);

        aci.first();
        int runStart = aci.getRunStart();
        if (runStart != 2) {
            throw new Exception("1st run start is wrong. ("+runStart+" should be 2.)");
        }

        int runLimit = aci.getRunLimit();
        if (runLimit != 3) {
            throw new Exception("1st run limit is wrong. ("+runLimit+" should be 3.)");
        }

        Object value = aci.getAttribute(TextAttribute.WEIGHT);
        if (value != TextAttribute.WEIGHT_LIGHT) {
            throw new Exception("1st run attribute is wrong. ("
                                +value+" should be "+TextAttribute.WEIGHT_LIGHT+".)");
        }

        value = aci.getAttribute(TextAttribute.WIDTH);
        if (value != null) {
            throw new Exception("1st run annotation is wrong. ("
                                +value+" should be null.)");
        }

        aci.setIndex(runLimit);
        runStart = aci.getRunStart();
        if (runStart != 3) {
            throw new Exception("2nd run start is wrong. ("+runStart+" should be 3.)");
        }

        runLimit = aci.getRunLimit();
        if (runLimit != 4) {
            throw new Exception("2nd run limit is wrong. ("+runLimit+" should be 4.)");
        }
        value = aci.getAttribute(TextAttribute.WEIGHT);
        if (value != TextAttribute.WEIGHT_BOLD) {
            throw new Exception("2nd run attribute is wrong. ("
                                +value+" should be "+TextAttribute.WEIGHT_BOLD+".)");
        }

        value = aci.getAttribute(TextAttribute.WIDTH);
        if (!(value instanceof Annotation)
            || (((Annotation)value).getValue() !=  TextAttribute.WIDTH_CONDENSED)) {
            throw new Exception("2nd run annotation is wrong. (" + value + " should be "
                                + new Annotation(TextAttribute.WIDTH_CONDENSED)+".)");
        }
    }
 
Example 12
Source File: MessageFormat.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Formats an array of objects and inserts them into the
 * <code>MessageFormat</code>'s pattern, producing an
 * <code>AttributedCharacterIterator</code>.
 * You can use the returned <code>AttributedCharacterIterator</code>
 * to build the resulting String, as well as to determine information
 * about the resulting String.
 * <p>
 * The text of the returned <code>AttributedCharacterIterator</code> is
 * the same that would be returned by
 * <blockquote>
 *     <code>{@link #format(java.lang.Object[], java.lang.StringBuffer,
 *     java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
 * </blockquote>
 * <p>
 * In addition, the <code>AttributedCharacterIterator</code> contains at
 * least attributes indicating where text was generated from an
 * argument in the <code>arguments</code> array. The keys of these attributes are of
 * type <code>MessageFormat.Field</code>, their values are
 * <code>Integer</code> objects indicating the index in the <code>arguments</code>
 * array of the argument from which the text was generated.
 * <p>
 * The attributes/value from the underlying <code>Format</code>
 * instances that <code>MessageFormat</code> uses will also be
 * placed in the resulting <code>AttributedCharacterIterator</code>.
 * This allows you to not only find where an argument is placed in the
 * resulting String, but also which fields it contains in turn.
 *
 * @param arguments an array of objects to be formatted and substituted.
 * @return AttributedCharacterIterator describing the formatted value.
 * @exception NullPointerException if <code>arguments</code> is null.
 * @throws IllegalArgumentException if a value in the
 *         <code>arguments</code> array is not of the type
 *         expected by the corresponding argument or custom Format object.
 */
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object arguments) {
    if (arguments == null) {
        throw new NullPointerException(
               "formatToCharacterIterator must be passed non-null object");
    }
    StringBuilder result = new StringBuilder();
    AppendableWrapper wrapper = new AppendableWrapper(result);
    wrapper.useAttributes();
    format(arguments, wrapper, null);
    AttributedString as = new AttributedString(result.toString());
    for (AttributeAndPosition a : wrapper.attributes) {
        as.addAttribute(a.key, a.value, a.start, a.limit);
    }
    return as.getIterator();
}
 
Example 13
Source File: Test.java    From tribaltrouble with GNU General Public License v2.0 4 votes vote down vote up
public final static void main(String[] args) {
		try {
			Display.setDisplayMode(new DisplayMode(DISPLAY_WIDTH, DISPLAY_HEIGHT));
			Display.create();
			initGL();

			// Load font
			InputStream font_is = Utils.makeURL("/fonts/tahoma.ttf").openStream();
			java.awt.Font src_font = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, font_is);
			java.awt.Font font = src_font.deriveFont(14f);

			// Load text
			InputStreamReader text_is = new InputStreamReader(Utils.makeURL("/test_text.txt").openStream());
			StringBuffer str_buffer = new StringBuffer();
			int c = text_is.read();
			do {
				str_buffer.append((char)c);
				c = text_is.read();
			} while (c != -1);
			String str = str_buffer.toString();

			// Build texture
			int[] pixels = new int[WIDTH*HEIGHT];
//			ByteBuffer pixel_data = ByteBuffer.wrap(pixels);						// NEW
//			pixelDataFromString(WIDTH, HEIGHT, str, font, pixels);					// NEW
			IntBuffer pixel_data = BufferUtils.createIntBuffer(WIDTH*HEIGHT);	// OLD
			pixel_data.put(pixels);													// OLD
			pixel_data.rewind();

			int texture_handle = createTexture(WIDTH, HEIGHT, pixel_data);
			
		FontRenderContext frc = g2d.getFontRenderContext();
		AttributedString att_str = new AttributedString(str);
		att_str.addAttribute(TextAttribute.FONT, font);
		AttributedCharacterIterator iterator = att_str.getIterator();
		LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
		
			while (!Display.isCloseRequested()) {
long start_time = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
pixelDataFromString(WIDTH, HEIGHT, str, font, pixels, measurer);
pixel_data.put(pixels); // OLD
pixel_data.rewind();

//texture_handle = createTexture(WIDTH, HEIGHT, pixel_data);
updateTexture(WIDTH, HEIGHT, pixel_data);
				GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
				GL11.glLoadIdentity();
				
				// Background
				/*
				GL11.glDisable(GL11.GL_TEXTURE_2D);
				GL11.glColor4f(.1f, .1f, .1f, 1f);
				GL11.glBegin(GL11.GL_QUADS);
				GL11.glVertex3f(0f, DISPLAY_HEIGHT-RENDER_SIZE, 1f);
				GL11.glVertex3f(RENDER_SIZE, DISPLAY_HEIGHT-RENDER_SIZE, 1f);
				GL11.glVertex3f(RENDER_SIZE, DISPLAY_HEIGHT, 1f);
				GL11.glVertex3f(0f, DISPLAY_HEIGHT, 1f);
				GL11.glEnd();
				*/

				// Text
				GL11.glEnable(GL11.GL_TEXTURE_2D);
				GL11.glColor4f(1f, 1f, 1f, 1f);
				GL11.glBegin(GL11.GL_QUADS);
				GL11.glTexCoord2f(0f, 1f);
				GL11.glVertex3f(0f, DISPLAY_HEIGHT-RENDER_SIZE, 1f);
				GL11.glTexCoord2f(1f, 1f);
				GL11.glVertex3f(RENDER_SIZE, DISPLAY_HEIGHT-RENDER_SIZE, 1f);
				GL11.glTexCoord2f(1f, 0f);
				GL11.glVertex3f(RENDER_SIZE, DISPLAY_HEIGHT, 1f);
				GL11.glTexCoord2f(0f, 0f);
				GL11.glVertex3f(0f, DISPLAY_HEIGHT, 1f);
				GL11.glEnd();
				Display.update();
}
long total_time = System.currentTimeMillis() - start_time;
System.out.println("total_time = " + total_time);

			}
			Display.destroy();
		} catch (Exception t) {
			t.printStackTrace();
		}
	}
 
Example 14
Source File: FontPanel.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private void calcFontMetrics( Graphics2D g2d, int w, int h ) {
    FontMetrics fm;
    Graphics2D g2 = (Graphics2D)g2d.create();

    /// ABP
    if ( g2Transform != NONE && textToUse != FILE_TEXT ) {
        g2.setFont( g2.getFont().deriveFont( getAffineTransform( g2Transform )) );
        fm = g2.getFontMetrics();
    }
    else {
        fm = g2.getFontMetrics();
    }

    maxAscent = fm.getMaxAscent();
    maxDescent = fm.getMaxDescent();
    if (maxAscent == 0) maxAscent = 10;
    if (maxDescent == 0) maxDescent = 5;
    if ( textToUse == RANGE_TEXT || textToUse == ALL_GLYPHS ) {
        /// Give slight extra room for each character
        maxAscent += 3;
        maxDescent += 3;
        gridWidth = fm.getMaxAdvance() + 6;
        gridHeight = maxAscent + maxDescent;
        if ( force16Cols )
          numCharAcross = 16;
        else
          numCharAcross = ( w - 10 ) / gridWidth;
        numCharDown = ( h - 10 ) / gridHeight;

        canvasInset_X = ( w - numCharAcross * gridWidth ) / 2;
        canvasInset_Y = ( h - numCharDown * gridHeight ) / 2;
        if ( numCharDown == 0 || numCharAcross == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );

        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() * numCharAcross );
    }
    else {
        maxDescent += fm.getLeading();
        canvasInset_X = 5;
        canvasInset_Y = 5;
        /// gridWidth and numCharAcross will not be used in this mode...
        gridHeight = maxAscent + maxDescent;
        numCharDown = ( h - canvasInset_Y * 2 ) / gridHeight;

        if ( numCharDown == 0 )
          throw new CannotDrawException( isPrinting ? CANT_FIT_PRINT : CANT_FIT_DRAW );
        /// If this is text loaded from file, prepares the LineBreak'ed
        /// text layout at this point
        if ( textToUse == FILE_TEXT ) {
            if ( !isPrinting )
              f2dt.fireChangeStatus( "LineBreaking Text... Please Wait", false );
            lineBreakTLs = new Vector();
            for ( int i = 0; i < fileText.length; i++ ) {
                AttributedString as =
                  new AttributedString( fileText[i], g2.getFont().getAttributes() );

                LineBreakMeasurer lbm =
                  new LineBreakMeasurer( as.getIterator(), g2.getFontRenderContext() );

                while ( lbm.getPosition() < fileText[i].length() )
                  lineBreakTLs.add( lbm.nextLayout( (float) w ));

            }
        }
        if ( !isPrinting )
          resetScrollbar( verticalBar.getValue() );
    }
}
 
Example 15
Source File: SerialUtilities.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Serialises an <code>AttributedString</code> object.
 *
 * @param as  the attributed string object (<code>null</code> permitted).
 * @param stream  the output stream (<code>null</code> not permitted).
 *
 * @throws IOException if there is an I/O error.
 */
public static void writeAttributedString(AttributedString as,
        ObjectOutputStream stream) throws IOException {

    if (stream == null) {
        throw new IllegalArgumentException("Null 'stream' argument.");
    }
    if (as != null) {
        stream.writeBoolean(false);
        AttributedCharacterIterator aci = as.getIterator();
        // build a plain string from aci
        // then write the string
        StringBuffer plainStr = new StringBuffer();
        char current = aci.first();
        while (current != CharacterIterator.DONE) {
            plainStr = plainStr.append(current);
            current = aci.next();
        }
        stream.writeObject(plainStr.toString());

        // then write the attributes and limits for each run
        current = aci.first();
        int begin = aci.getBeginIndex();
        while (current != CharacterIterator.DONE) {
            // write the current character - when the reader sees that this
            // is not CharacterIterator.DONE, it will know to read the
            // run limits and attributes
            stream.writeChar(current);

            // now write the limit, adjusted as if beginIndex is zero
            int limit = aci.getRunLimit();
            stream.writeInt(limit - begin);

            // now write the attribute set
            Map atts = new HashMap(aci.getAttributes());
            stream.writeObject(atts);
            current = aci.setIndex(limit);
        }
        // write a character that signals to the reader that all runs
        // are done...
        stream.writeChar(CharacterIterator.DONE);
    }
    else {
        // write a flag that indicates a null
        stream.writeBoolean(true);
    }

}
 
Example 16
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight) {
    int availableHeight = boxHeight - ICON_SIZE - ICON_PADDING;

    // Create an attributed string based in input text
    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, g.getFont());
    attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);

    AttributedCharacterIterator characterIterator = attributedString.getIterator();

    int width = boxWidth - (2 * TEXT_PADDING);

    int currentHeight = 0;
    // Prepare a list of lines of text we'll be drawing
    List<TextLayout> layouts = new ArrayList<TextLayout>();
    String lastLine = null;

    LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());

    TextLayout layout = null;
    while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= availableHeight) {

        int previousPosition = measurer.getPosition();

        // Request next layout
        layout = measurer.nextLayout(width);

        int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();

        if (currentHeight + height > availableHeight) {
            // The line we're about to add should NOT be added anymore, append three dots to previous one instead
            // to indicate more text is truncated
            layouts.remove(layouts.size() - 1);

            if (lastLine.length() >= 4) {
                lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
            }
            layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
        } else {
            layouts.add(layout);
            lastLine = text.substring(previousPosition, measurer.getPosition());
            currentHeight += height;
        }
    }


    int currentY = y + ICON_SIZE + ICON_PADDING + ((availableHeight - currentHeight) / 2);
    int currentX = 0;

    // Actually draw the lines
    for (TextLayout textLayout : layouts) {

        currentY += textLayout.getAscent();
        currentX = TEXT_PADDING + x + ((width - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2);

        textLayout.draw(g, currentX, currentY);
        currentY += textLayout.getDescent() + textLayout.getLeading();
    }

}
 
Example 17
Source File: MessageFormat.java    From fitnotifications with Apache License 2.0 4 votes vote down vote up
/**
 * Formats an array of objects and inserts them into the
 * <code>MessageFormat</code>'s pattern, producing an
 * <code>AttributedCharacterIterator</code>.
 * You can use the returned <code>AttributedCharacterIterator</code>
 * to build the resulting String, as well as to determine information
 * about the resulting String.
 * <p>
 * The text of the returned <code>AttributedCharacterIterator</code> is
 * the same that would be returned by
 * <blockquote>
 *     <code>{@link #format(java.lang.Object[], java.lang.StringBuffer,
 *     java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
 * </blockquote>
 * <p>
 * In addition, the <code>AttributedCharacterIterator</code> contains at
 * least attributes indicating where text was generated from an
 * argument in the <code>arguments</code> array. The keys of these attributes are of
 * type <code>MessageFormat.Field</code>, their values are
 * <code>Integer</code> objects indicating the index in the <code>arguments</code>
 * array of the argument from which the text was generated.
 * <p>
 * The attributes/value from the underlying <code>Format</code>
 * instances that <code>MessageFormat</code> uses will also be
 * placed in the resulting <code>AttributedCharacterIterator</code>.
 * This allows you to not only find where an argument is placed in the
 * resulting String, but also which fields it contains in turn.
 *
 * @param arguments an array of objects to be formatted and substituted.
 * @return AttributedCharacterIterator describing the formatted value.
 * @exception NullPointerException if <code>arguments</code> is null.
 * @throws IllegalArgumentException if a value in the
 *         <code>arguments</code> array is not of the type
 *         expected by the corresponding argument or custom Format object.
 * @stable ICU 3.8
 */
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object arguments) {
    if (arguments == null) {
        throw new NullPointerException(
               "formatToCharacterIterator must be passed non-null object");
    }
    StringBuilder result = new StringBuilder();
    AppendableWrapper wrapper = new AppendableWrapper(result);
    wrapper.useAttributes();
    format(arguments, wrapper, null);
    AttributedString as = new AttributedString(result.toString());
    for (AttributeAndPosition a : wrapper.attributes) {
        as.addAttribute(a.key, a.value, a.start, a.limit);
    }
    return as.getIterator();
}
 
Example 18
Source File: DefaultCaseDiagramCanvas.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight, boolean centered) {
    // Create an attributed string based in input text
    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, g.getFont());
    attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);

    AttributedCharacterIterator characterIterator = attributedString.getIterator();

    int currentHeight = 0;
    // Prepare a list of lines of text we'll be drawing
    List<TextLayout> layouts = new ArrayList<>();
    String lastLine = null;

    LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());

    TextLayout layout = null;
    while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= boxHeight) {

        int previousPosition = measurer.getPosition();

        // Request next layout
        layout = measurer.nextLayout(boxWidth);

        int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();

        if (currentHeight + height > boxHeight) {
            // The line we're about to add should NOT be added anymore, append three dots to previous one instead
            // to indicate more text is truncated
            if (!layouts.isEmpty()) {
                layouts.remove(layouts.size() - 1);

                if (lastLine.length() >= 4) {
                    lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
                }
                layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
            }
            break;
        } else {
            layouts.add(layout);
            lastLine = text.substring(previousPosition, measurer.getPosition());
            currentHeight += height;
        }
    }

    int currentY = y + (centered ? ((boxHeight - currentHeight) / 2) : 0);
    int currentX = 0;

    // Actually draw the lines
    for (TextLayout textLayout : layouts) {

        currentY += textLayout.getAscent();
        currentX = x + (centered ? ((boxWidth - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2) : 0);

        textLayout.draw(g, currentX, currentY);
        currentY += textLayout.getDescent() + textLayout.getLeading();
    }

}
 
Example 19
Source File: ProcessDiagramCanvas.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
protected void drawMultilineText(String text, int x, int y, int boxWidth, int boxHeight) {
    int availableHeight = boxHeight - ICON_SIZE - ICON_PADDING;

    // Create an attributed string based in input text
    AttributedString attributedString = new AttributedString(text);
    attributedString.addAttribute(TextAttribute.FONT, g.getFont());
    attributedString.addAttribute(TextAttribute.FOREGROUND, Color.black);

    AttributedCharacterIterator characterIterator = attributedString.getIterator();

    int width = boxWidth - (2 * TEXT_PADDING);

    int currentHeight = 0;
    // Prepare a list of lines of text we'll be drawing
    List<TextLayout> layouts = new ArrayList<TextLayout>();
    String lastLine = null;

    LineBreakMeasurer measurer = new LineBreakMeasurer(characterIterator, g.getFontRenderContext());

    TextLayout layout = null;
    while (measurer.getPosition() < characterIterator.getEndIndex() && currentHeight <= availableHeight) {

        int previousPosition = measurer.getPosition();

        // Request next layout
        layout = measurer.nextLayout(width);

        int height = ((Float) (layout.getDescent() + layout.getAscent() + layout.getLeading())).intValue();

        if (currentHeight + height > availableHeight) {
            // The line we're about to add should NOT be added anymore, append three dots to previous one instead
            // to indicate more text is truncated
            layouts.remove(layouts.size() - 1);

            if (lastLine.length() >= 4) {
                lastLine = lastLine.substring(0, lastLine.length() - 4) + "...";
            }
            layouts.add(new TextLayout(lastLine, g.getFont(), g.getFontRenderContext()));
        } else {
            layouts.add(layout);
            lastLine = text.substring(previousPosition, measurer.getPosition());
            currentHeight += height;
        }
    }


    int currentY = y + ICON_SIZE + ICON_PADDING + ((availableHeight - currentHeight) / 2);
    int currentX = 0;

    // Actually draw the lines
    for (TextLayout textLayout : layouts) {

        currentY += textLayout.getAscent();
        currentX = TEXT_PADDING + x + ((width - ((Double) textLayout.getBounds().getWidth()).intValue()) / 2);

        textLayout.draw(g, currentX, currentY);
        currentY += textLayout.getDescent() + textLayout.getLeading();
    }

}
 
Example 20
Source File: AttrStringUtils.java    From ccu-historian with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Returns the bounds for the attributed string.
 * 
 * @param text  the attributed string (<code>null</code> not permitted).
 * @param g2  the graphics target (<code>null</code> not permitted).
 * 
 * @return The bounds (never <code>null</code>).
 * 
 * @since 1.0.18
 */
public static Rectangle2D getTextBounds(AttributedString text, 
        Graphics2D g2) {
    TextLayout tl = new TextLayout(text.getIterator(), 
            g2.getFontRenderContext());
    return tl.getBounds();
}