Java Code Examples for java.awt.font.LineBreakMeasurer.nextLayout()

The following are Jave code examples for showing how to use nextLayout() of the java.awt.font.LineBreakMeasurer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: FreeCol   File: FreeColToolTipUI.java   View Source Code Vote up 6 votes
@Override
public Dimension getPreferredSize(JComponent c) {
    String tipText = ((JToolTip)c).getTipText();
    if (tipText == null || tipText.isEmpty()) {
        return new Dimension(0, 0);
    }

    float x = 0f;
    float y = 0f;
    for (String line : lineBreak.split(tipText)) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText
            = new AttributedString(line).getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            x = Math.max(x, layout.getVisibleAdvance());
            y += layout.getAscent() + layout.getDescent() + layout.getLeading();

        }
    }
    return new Dimension((int) (x + 2 * margin),
                         (int) (y + 2 * margin));

}
 
Example 2
Project: hopsworks   File: GraphicsUtils.java   View Source Code Vote up 6 votes
private static void drawTextInBoundedArea(Graphics2D g2d, int x1, int y1,
        int x2, int y2, String text) {
  float interline = 1;
  float width = x2 - x1;
  AttributedString as = new AttributedString(text);
  as.addAttribute(TextAttribute.FOREGROUND, g2d.getPaint());
  as.addAttribute(TextAttribute.FONT, g2d.getFont());
  AttributedCharacterIterator aci = as.getIterator();
  FontRenderContext frc = new FontRenderContext(null, true, false);
  LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
  while (lbm.getPosition() < text.length()) {
    TextLayout tl = lbm.nextLayout(width);
    y1 += tl.getAscent();
    tl.draw(g2d, x1, y1);
    y1 += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.
            getAscent();
    if (y1 > y2) {
      break;
    }
  }
}
 
Example 3
Project: tribaltrouble   File: Test.java   View Source Code Vote up 6 votes
private final static void pixelDataFromString(int width, int height, String str, java.awt.Font font, int[] pixels, LineBreakMeasurer measurer) {
	measurer.setPosition(0);
	g2d.clearRect(0, 0, width, height);
	g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	float wrapping_width = width;
	float y = 0;
	int length = str.length();
	while (measurer.getPosition() < length) {
		TextLayout layout = measurer.nextLayout(wrapping_width);
		y += (layout.getAscent());
		float x = layout.isLeftToRight() ? 0 : (wrapping_width - layout.getAdvance());

		layout.draw(g2d, x, y);
		y += layout.getDescent() + layout.getLeading();
	}
	image.getRaster().getDataElements(0, 0, image.getWidth(), image.getHeight(), pixels);
}
 
Example 4
Project: studio   File: DefaultPrintable.java   View Source Code Vote up 6 votes
/**
* @param wrappingWidth width of the layout
* @param frCtx for possible new instance of LineBreakMeasurer
* @return next TextLayout that is to be rendered
*/
private TextLayout nextLayout(float wrappingWidth, FontRenderContext frc) {
    TextLayout l;

    if (currentLayout == textLayouts.size()) {
        LineBreakMeasurer old = lineBreakMeasurer;
        LineBreakMeasurer measurer = getMeasurer(frc);
        if (measurer == null) {
            return null;
        }
        l = measurer.nextLayout(wrappingWidth);
        textLayouts.add(l);

        if (old != measurer) { // new line
            startLayouts.add(l);
        }

    } else {
        l = (TextLayout) textLayouts.get(currentLayout);
    }
    currentLayout++; // advance to next
    return l;
}
 
Example 5
Project: jrunalyzer   File: SelectedWaypointRenderer.java   View Source Code Vote up 6 votes
private void drawText(Graphics2D g2, String text, float width) {
	FontRenderContext frc = g2.getFontRenderContext();

	AttributedString styledText = new AttributedString(text);
	AttributedCharacterIterator aci = styledText.getIterator();
	int start = aci.getBeginIndex();
	int end = aci.getEndIndex();
	LineBreakMeasurer measurer = new LineBreakMeasurer(aci, frc);
	measurer.setPosition(start);

	float x = 0, y = 0;
	while (measurer.getPosition() < end) {
		TextLayout layout = measurer.nextLayout(width);

		y += layout.getAscent();
		float dx = layout.isLeftToRight() ? 0 : width - layout.getAdvance();

		layout.draw(g2, x + dx, y);
		y += layout.getDescent() + layout.getLeading();
	}
}
 
Example 6
Project: reactome2gpml-converter   File: ReactomeToGPMLConverter.java   View Source Code Vote up 6 votes
private String wrapLines(String s, float wrappingWidth, FontRenderContext frc, String lineBreak) {
    AttributedCharacterIterator aci = new AttributedString(s).getIterator();
    int end = aci.getEndIndex();
    LineBreakMeasurer measurer = new LineBreakMeasurer(aci, frc);
    StringBuffer output = new StringBuffer();
    int position = 0;
    int lastPosition = 0;
    do {
        measurer.nextLayout(wrappingWidth);
        position = measurer.getPosition();
        output.append(s, lastPosition, position);
        output.append(lineBreak);
        lastPosition = position;
    } while (position < end);
    return output.toString();
}
 
Example 7
Project: SOEN6471-FreeCol   File: FreeColToolTipUI.java   View Source Code Vote up 6 votes
public Dimension getPreferredSize(JComponent c) {
    String tipText = ((JToolTip)c).getTipText();
    if (tipText == null) {
        return new Dimension(0, 0);
    }

    float x = 0f;
    float y = 0f;
    for (String line : lineBreak.split(((JToolTip) c).getTipText())) {
        AttributedCharacterIterator styledText
            = new AttributedString(line).getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            x = Math.max(x, layout.getVisibleAdvance());
            y += layout.getAscent() + layout.getDescent() + layout.getLeading();

        }
    }
    return new Dimension((int) (x + 2 * margin),
                         (int) (y + 2 * margin));

}
 
Example 8
Project: Harmonia-1.5   File: MessageController.java   View Source Code Vote up 6 votes
private static int countLines(JTextArea textArea)
{
	AttributedString text = new AttributedString(textArea.getText());
	FontRenderContext frc = textArea.getFontMetrics(textArea.getFont()).getFontRenderContext();
	AttributedCharacterIterator charIt = text.getIterator();
	LineBreakMeasurer lbm = new LineBreakMeasurer(charIt, frc);
	float formatWidth = (float) textArea.getSize().width;
	lbm.setPosition(charIt.getBeginIndex());
	
	int numLines =0;
	while (lbm.getPosition()<charIt.getEndIndex())
	{
		lbm.nextLayout(formatWidth);
		numLines++;
	}	
	return numLines;
}
 
Example 9
Project: spark-svn-mirror   File: JMultilineLabel.java   View Source Code Vote up 6 votes
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 10
Project: litiengine   File: SpeechBubble.java   View Source Code Vote up 5 votes
@Override
public void render(final Graphics2D g) {
  if (this.displayedText == null || this.displayedText.isEmpty() || !Game.getRenderEngine().canRender(this.entity)) {
    return;
  }

  final Point2D location = Game.getCamera().getViewPortLocation(this.entity);
  RenderEngine.renderImage(g, this.bubble, new Point2D.Double(location.getX() + this.entity.getWidth() / 2.0 - this.textBoxWidth / 2.0 - PADDING, location.getY() - this.height - PADDING));

  g.setColor(SPEAK_FONT_COLOR);
  final FontRenderContext frc = g.getFontRenderContext();

  final String text = this.displayedText;
  final AttributedString styledText = new AttributedString(text);
  styledText.addAttribute(TextAttribute.FONT, this.font);
  final AttributedCharacterIterator iterator = styledText.getIterator();
  final LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
  measurer.setPosition(0);
  final float x = (float) Game.getCamera().getViewPortLocation(this.entity).getX() + this.entity.getWidth() / 2.0f - this.textBoxWidth / 2.0f;
  float y = (float) Game.getCamera().getViewPortLocation(this.entity).getY() - this.height;
  while (measurer.getPosition() < text.length()) {
    final TextLayout layout = measurer.nextLayout(this.textBoxWidth);

    y += layout.getAscent();
    final float dx = layout.isLeftToRight() ? 0 : this.textBoxWidth - layout.getAdvance();
    layout.draw(g, x + dx, y);
    y += layout.getDescent() + layout.getLeading();
  }
}
 
Example 11
Project: freecol   File: FreeColToolTipUI.java   View Source Code Vote up 5 votes
@Override
public void paint(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        ImageLibrary.drawTiledImage("image.background.FreeColToolTip", g, c, null);
    }

    g.setColor(Color.BLACK); // FIXME: find out why this is necessary

    Graphics2D graphics = (Graphics2D)g;
    float x = margin;
    float y = margin;
    for (String line : lineBreak.split(((JToolTip) c).getTipText())) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText =
            new AttributedString(line).getIterator();

        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            y += (layout.getAscent());
            float dx = layout.isLeftToRight() ?
                0 : (maximumWidth - layout.getAdvance());

            layout.draw(graphics, x + dx, y);
            y += layout.getDescent() + layout.getLeading();
        }
    }
 }
 
Example 12
Project: freecol   File: FreeColToolTipUI.java   View Source Code Vote up 5 votes
@Override
public Dimension getPreferredSize(JComponent c) {
    String tipText = ((JToolTip)c).getTipText();
    if (tipText == null || tipText.isEmpty()) {
        return new Dimension(0, 0);
    }

    float x = 0f;
    float y = 0f;
    for (String line : lineBreak.split(tipText)) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText
            = new AttributedString(line).getIterator();
        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            x = Math.max(x, layout.getVisibleAdvance());
            y += layout.getAscent() + layout.getDescent() + layout.getLeading();

        }
    }
    return new Dimension((int) (x + 2 * margin),
                         (int) (y + 2 * margin));

}
 
Example 13
Project: openjdk-jdk10   File: TestLineBreakWithFontSub.java   View Source Code Vote up 5 votes
public void test() {

        // construct a paragraph as follows: MIXED + [SPACING + WORD] + ...
        StringBuffer text = new StringBuffer(MIXED);
        for (int i=0; i < NUM_WORDS; i++) {
            text.append(SPACING);
            text.append(WORD);
        }

        AttributedString attrString = new AttributedString(text.toString());
        attrString.addAttribute(TextAttribute.SIZE, new Float(24.0));

        LineBreakMeasurer measurer = new LineBreakMeasurer(attrString.getIterator(),
                                                           DEFAULT_FRC);

        // get width of a space-word sequence, in context
        int sequenceLength = WORD.length()+SPACING.length();
        measurer.setPosition(text.length() - sequenceLength);

        TextLayout layout = measurer.nextLayout(10000.0f);

        if (layout.getCharacterCount() != sequenceLength) {
            throw new Error("layout length is incorrect!");
        }

        final float sequenceAdvance = layout.getVisibleAdvance();

        float wrappingWidth = sequenceAdvance * 2;

        // now run test with a variety of widths
        while (wrappingWidth < (sequenceAdvance*NUM_WORDS)) {
            measurer.setPosition(0);
            checkMeasurer(measurer,
                          wrappingWidth,
                          sequenceAdvance,
                          text.length());
            wrappingWidth += sequenceAdvance / 5;
        }
    }
 
Example 14
Project: openjdk-jdk10   File: TestLineBreakWithFontSub.java   View Source Code Vote up 5 votes
/**
 * Iterate through measurer and check that every line is
 * not too long and not too short, but just right.
 */
private void checkMeasurer(LineBreakMeasurer measurer,
                           float wrappingWidth,
                           float sequenceAdvance,
                           int endPosition) {

    do {
        TextLayout layout = measurer.nextLayout(wrappingWidth);
        float visAdvance = layout.getVisibleAdvance();

        // Check that wrappingWidth-sequenceAdvance < visAdvance
        // Also, if we're not at the end of the paragraph,
        // check that visAdvance <= wrappingWidth

        if (visAdvance > wrappingWidth) {
            // line is too long for given wrapping width
            throw new Error("layout is too long");
        }

        if (measurer.getPosition() < endPosition) {
            if (visAdvance <= wrappingWidth - sequenceAdvance) {
                // line is too short for given wrapping width;
                // another word would have fit
                throw new Error("room for more words on line.  diff=" +
                                (wrappingWidth - sequenceAdvance - visAdvance));
            }
        }
    } while (measurer.getPosition() != endPosition);
}
 
Example 15
Project: FreeCol   File: FreeColToolTipUI.java   View Source Code Vote up 5 votes
@Override
public void paint(Graphics g, JComponent c) {
    if (c.isOpaque()) {
        ImageLibrary.drawTiledImage("image.background.FreeColToolTip", g, c, null);
    }

    g.setColor(Color.BLACK); // FIXME: find out why this is necessary

    Graphics2D graphics = (Graphics2D)g;
    float x = margin;
    float y = margin;
    for (String line : lineBreak.split(((JToolTip) c).getTipText())) {
        if (line.isEmpty()) {
            y += LEADING;
            continue;
        }
        AttributedCharacterIterator styledText =
            new AttributedString(line).getIterator();

        LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

        while (measurer.getPosition() < styledText.getEndIndex()) {

            TextLayout layout = measurer.nextLayout(maximumWidth);

            y += (layout.getAscent());
            float dx = layout.isLeftToRight() ?
                0 : (maximumWidth - layout.getAdvance());

            layout.draw(graphics, x + dx, y);
            y += layout.getDescent() + layout.getLeading();
        }
    }
 }
 
Example 16
Project: DigitalMediaServer   File: SwingUtils.java   View Source Code Vote up 5 votes
/**
 * Returns the {@link Dimension} for the given {@link JTextComponent}
 * subclass that will show the whole word wrapped text in the given width.
 * It won't work for styled text of varied size or style, it's assumed that
 * the whole text is rendered with the {@link JTextComponent}s font.
 *
 * @param textComponent the {@link JTextComponent} to calculate the {@link Dimension} for
 * @param width the width of the resulting {@link Dimension}
 * @param text the {@link String} which should be word wrapped
 * @return The calculated {@link Dimension}
 */
public static Dimension getWordWrappedTextDimension(JTextComponent textComponent, int width, String text) {
	if (textComponent == null) {
		throw new IllegalArgumentException("textComponent cannot be null");
	}
	if (width < 1) {
		throw new IllegalArgumentException("width must be 1 or greater");
	}
	if (text == null) {
		text = textComponent.getText();
	}
	if (text.isEmpty()) {
		return new Dimension(width, 0);
	}

	FontMetrics metrics = textComponent.getFontMetrics(textComponent.getFont());
    FontRenderContext rendererContext = metrics.getFontRenderContext();
    float formatWidth = width - textComponent.getInsets().left - textComponent.getInsets().right;

    int lines = 0;
    String[] paragraphs = text.split("\n");
    for (String paragraph : paragraphs) {
    	if (paragraph.isEmpty()) {
    		lines++;
    	} else {
			AttributedString attributedText = new AttributedString(paragraph);
			attributedText.addAttribute(TextAttribute.FONT, textComponent.getFont());
		    AttributedCharacterIterator charIterator = attributedText.getIterator();
		    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIterator, rendererContext);

		    lineMeasurer.setPosition(charIterator.getBeginIndex());
		    while (lineMeasurer.getPosition() < charIterator.getEndIndex()) {
		    	lineMeasurer.nextLayout(formatWidth);
		    	lines++;
		    }
    	}
    }

    return new Dimension(width, metrics.getHeight() * lines + textComponent.getInsets().top + textComponent.getInsets().bottom);
}
 
Example 17
Project: PhET   File: PStyledText.java   View Source Code Vote up 5 votes
private ArrayList extractLineBreaks(final AttributedCharacterIterator itr, final LineBreakMeasurer measurer) {
    ArrayList breakList;
    breakList = new ArrayList();
    while (measurer.getPosition() < itr.getEndIndex()) {
        if (constrainWidthToTextWidth) {
            measurer.nextLayout(Float.MAX_VALUE);
        }
        else {
            measurer.nextLayout((float) Math.ceil(getWidth() - insets.left - insets.right));
        }

        breakList.add(new Integer(measurer.getPosition()));
    }
    return breakList;
}
 
Example 18
Project: jasperreports   File: ComplexTextLineWrapper.java   View Source Code Vote up 5 votes
@Override
public TextLine baseTextLine(int index)
{
	AttributedString tmpText = new AttributedString(paragraph, index, index + 1);
	LineBreakMeasurer lbm = new LineBreakMeasurer(tmpText.getIterator(), context.getFontRenderContext());
	TextLayout tlyt = lbm.nextLayout(100);//FIXME what is this? why 100?
	return new TextLayoutLine(tlyt);
}
 
Example 19
Project: pumpernickel   File: DecoratedPanelUIDemo.java   View Source Code Vote up 5 votes
@Override
public void paint(Graphics g, JComponent c) {
	Graphics2D g2 = (Graphics2D)g.create();
	try {
		if(icon!=null) {
			Dimension d = icon.getPreferredSize(c.getWidth()*3/4, c.getHeight()*3/4);
			icon.paintIcon(c, g2, c.getWidth()/2 - d.width/2, c.getHeight()/2 - d.height/2, d.width, d.height);
		}
		
		g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		if(attrString!=null) {
			float y = 0;
			for(int a = 0; a<attrString.length; a++) {
				LineBreakMeasurer lbm = new LineBreakMeasurer(attrString[a].getIterator(), g2.getFontRenderContext());
				TextLayout tl = lbm.nextLayout(c.getWidth());
				while(tl!=null) {
					y += tl.getAscent();
					tl.draw(g2, 0, y);
					y += tl.getDescent() + tl.getLeading();
					
					tl = lbm.nextLayout(c.getWidth());
				}
			}
		}
		
		if(mouseInside) {
			g2.setStroke(new BasicStroke(2, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 10, new float[] {4, 4}, 0));
			g2.draw(new Rectangle(0, 0, c.getWidth(), c.getHeight()));
		}
	} finally {
		g2.dispose();
	}
}
 
Example 20
Project: pumpernickel   File: TextBoxPaintable.java   View Source Code Vote up 5 votes
public TextBoxPaintable(String string,Font font,float maxWidth,float insets,Paint paint) {
	if(paint==null)
		paint = SystemColor.textText;
	this.insets = insets;
	this.text = string;
	this.paint = paint;
	
	List<String> lines = new ArrayList<String>();
	Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
	attributes.put( TextAttribute.FONT, font);
	AttributedString attrString = new AttributedString(string, attributes);
	LineBreakMeasurer lbm = new LineBreakMeasurer( attrString.getIterator(), frc);
	TextLayout tl = lbm.nextLayout(maxWidth);
	float dy = 0;
	GeneralPath path = new GeneralPath();
	int startIndex = 0;
	while(tl!=null) {
		path.append( tl.getOutline( AffineTransform.getTranslateInstance(0, dy) ), false );
		dy += tl.getAscent()+tl.getDescent()+tl.getLeading();
		int charCount = tl.getCharacterCount();
		lines.add( text.substring(startIndex, startIndex+charCount) );
		startIndex += charCount;
		tl = lbm.nextLayout(maxWidth);
	}
	this.lines = lines.toArray(new String[lines.size()]);
	untransformedShape = path;
	Rectangle2D b = ShapeBounds.getBounds(untransformedShape);
	b.setFrame(b.getX(), b.getY(), b.getWidth() + 2*insets, b.getHeight() + 2*insets);
	untransformedBounds = b.getBounds();
}
 
Example 21
Project: jdk8u_jdk   File: TestLineBreakWithFontSub.java   View Source Code Vote up 5 votes
public void test() {

        // construct a paragraph as follows: MIXED + [SPACING + WORD] + ...
        StringBuffer text = new StringBuffer(MIXED);
        for (int i=0; i < NUM_WORDS; i++) {
            text.append(SPACING);
            text.append(WORD);
        }

        AttributedString attrString = new AttributedString(text.toString());
        attrString.addAttribute(TextAttribute.SIZE, new Float(24.0));

        LineBreakMeasurer measurer = new LineBreakMeasurer(attrString.getIterator(),
                                                           DEFAULT_FRC);

        // get width of a space-word sequence, in context
        int sequenceLength = WORD.length()+SPACING.length();
        measurer.setPosition(text.length() - sequenceLength);

        TextLayout layout = measurer.nextLayout(10000.0f);

        if (layout.getCharacterCount() != sequenceLength) {
            throw new Error("layout length is incorrect!");
        }

        final float sequenceAdvance = layout.getVisibleAdvance();

        float wrappingWidth = sequenceAdvance * 2;

        // now run test with a variety of widths
        while (wrappingWidth < (sequenceAdvance*NUM_WORDS)) {
            measurer.setPosition(0);
            checkMeasurer(measurer,
                          wrappingWidth,
                          sequenceAdvance,
                          text.length());
            wrappingWidth += sequenceAdvance / 5;
        }
    }
 
Example 22
Project: jdk8u_jdk   File: TestLineBreakWithFontSub.java   View Source Code Vote up 5 votes
/**
 * Iterate through measurer and check that every line is
 * not too long and not too short, but just right.
 */
private void checkMeasurer(LineBreakMeasurer measurer,
                           float wrappingWidth,
                           float sequenceAdvance,
                           int endPosition) {

    do {
        TextLayout layout = measurer.nextLayout(wrappingWidth);
        float visAdvance = layout.getVisibleAdvance();

        // Check that wrappingWidth-sequenceAdvance < visAdvance
        // Also, if we're not at the end of the paragraph,
        // check that visAdvance <= wrappingWidth

        if (visAdvance > wrappingWidth) {
            // line is too long for given wrapping width
            throw new Error("layout is too long");
        }

        if (measurer.getPosition() < endPosition) {
            if (visAdvance <= wrappingWidth - sequenceAdvance) {
                // line is too short for given wrapping width;
                // another word would have fit
                throw new Error("room for more words on line.  diff=" +
                                (wrappingWidth - sequenceAdvance - visAdvance));
            }
        }
    } while (measurer.getPosition() != endPosition);
}
 
Example 23
Project: flowable-engine   File: DefaultProcessDiagramCanvas.java   View Source Code Vote up 5 votes
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 24
Project: flowable-engine   File: DefaultProcessDiagramCanvas.java   View Source Code Vote up 5 votes
public void drawLabel(String text, GraphicInfo graphicInfo, boolean centered) {
    float interline = 1.0f;

    // text
    if (text != null && text.length() > 0) {
        Paint originalPaint = g.getPaint();
        Font originalFont = g.getFont();

        g.setPaint(LABEL_COLOR);
        g.setFont(LABEL_FONT);

        int wrapWidth = 100;
        int textY = (int) graphicInfo.getY();

        // TODO: use drawMultilineText()
        AttributedString as = new AttributedString(text);
        as.addAttribute(TextAttribute.FOREGROUND, g.getPaint());
        as.addAttribute(TextAttribute.FONT, g.getFont());
        AttributedCharacterIterator aci = as.getIterator();
        FontRenderContext frc = new FontRenderContext(null, true, false);
        LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);

        while (lbm.getPosition() < text.length()) {
            TextLayout tl = lbm.nextLayout(wrapWidth);
            textY += tl.getAscent();
            Rectangle2D bb = tl.getBounds();
            double tX = graphicInfo.getX();
            if (centered) {
                tX += (int) (graphicInfo.getWidth() / 2 - bb.getWidth() / 2);
            }
            tl.draw(g, (float) tX, textY);
            textY += tl.getDescent() + tl.getLeading() + (interline - 1.0f) * tl.getAscent();
        }

        // restore originals
        g.setFont(originalFont);
        g.setPaint(originalPaint);
    }
}
 
Example 25
Project: playn   File: JavaTextLayout.java   View Source Code Vote up 5 votes
public static JavaTextLayout[] layoutText (JavaGraphics gfx, String text, TextFormat format,
                                           TextWrap wrap) {
  // normalize newlines in the text (Windows: CRLF -> LF, Mac OS pre-X: CR -> LF)
  text = normalizeEOL(text);

  // we do some fiddling to work around the fact that TextLayout chokes on the empty string
  String ltext = text.length() == 0 ? " " : text;

  // set up an attributed character iterator so that we can measure the text
  AttributedString astring = new AttributedString(ltext);
  if (format.font != null) {
    astring.addAttribute(TextAttribute.FONT, gfx.resolveFont(format.font));
  }

  List<JavaTextLayout> layouts = new ArrayList<JavaTextLayout>();
  FontRenderContext frc = format.antialias ? gfx.aaFontContext() : gfx.aFontContext();
  LineBreakMeasurer measurer = new LineBreakMeasurer(astring.getIterator(), frc);
  int lastPos = ltext.length(), curPos = 0;
  char eol = '\n';
  while (curPos < lastPos) {
    int nextRet = ltext.indexOf(eol, measurer.getPosition()+1);
    if (nextRet == -1) {
      nextRet = lastPos;
    }
    TextLayout layout = measurer.nextLayout(wrap.width, nextRet, false);
    int endPos = measurer.getPosition();
    while (curPos < endPos && ltext.charAt(curPos) == eol)
      curPos += 1; // skip over EOLs
    layouts.add(new JavaTextLayout(ltext.substring(curPos, endPos), format, layout));
    curPos = endPos;
  }
  return layouts.toArray(new JavaTextLayout[layouts.size()]);
}
 
Example 26
Project: esadb   File: GraphicsString.java   View Source Code Vote up 5 votes
private int getStringWidth(AttributedCharacterIterator s) {
    FontRenderContext fontRenderContext = g.getFontRenderContext();
    LineBreakMeasurer lbm = new LineBreakMeasurer(s, fontRenderContext);
    TextLayout textLayout = lbm.nextLayout(Integer.MAX_VALUE);
    if (textLayout == null) return 0;
    return (int) textLayout.getBounds().getWidth();
}
 
Example 27
Project: piccolo2d.java   File: PStyledText.java   View Source Code Vote up 5 votes
private ArrayList extractLineBreaks(final AttributedCharacterIterator itr, final LineBreakMeasurer measurer) {
    ArrayList breakList;
    breakList = new ArrayList();
    while (measurer.getPosition() < itr.getEndIndex()) {
        if (constrainWidthToTextWidth) {
            measurer.nextLayout(Float.MAX_VALUE);
        }
        else {
            measurer.nextLayout((float) Math.ceil(getWidth() - insets.left - insets.right));
        }

        breakList.add(new Integer(measurer.getPosition()));
    }
    return breakList;
}
 
Example 28
Project: firebird-vizualization-tool   File: MultilineLayouter.java   View Source Code Vote up 5 votes
/**
 * Calculates the layout.
 * @param fontRenderContext the FontRenderContext
 * @param font the Font
 * @param text the text
 * @param layoutWidth the width of the layout area
 * @return the layout result
 */
public MultilineLayout calculateLayout(FontRenderContext fontRenderContext,
  Font font, String text, double layoutWidth) {
  // Layout multiline text
  MultilineLayout result = new MultilineLayout();
  if (text == null || text.isEmpty()) return result;
  Map<TextAttribute, Object> styleMap = new HashMap<TextAttribute, Object>();
  styleMap.put(TextAttribute.FONT, font);
  String[] textlines = text.split("\n");
  double height = 0;
  for (String textline : textlines) {
    AttributedString attribText = new AttributedString(textline, styleMap);
    AttributedCharacterIterator iter = attribText.getIterator();
    int textStart = iter.getBeginIndex();
    int textEnd = iter.getEndIndex();
    LineBreakMeasurer measurer = new LineBreakMeasurer(iter,
      fontRenderContext);
    measurer.setPosition(textStart);
    while (measurer.getPosition() < textEnd) {
      TextLayout line = measurer.nextLayout((float) layoutWidth);
      result.addLine(line);
      height += (line.getAscent() + line.getDescent() + line.getLeading());
    }
  }
  result.setSize(layoutWidth, height);
  return result;
}
 
Example 29
Project: calao   File: RoundedButton.java   View Source Code Vote up 5 votes
double getWidthOfAttributedString(Graphics2D graphics2D, AttributedString attributedString) {
    AttributedCharacterIterator characterIterator = attributedString.getIterator();
    FontRenderContext fontRenderContext = graphics2D.getFontRenderContext();
    LineBreakMeasurer lbm = new LineBreakMeasurer(characterIterator, fontRenderContext);
    TextLayout textLayout = lbm.nextLayout(Integer.MAX_VALUE);
    return textLayout.getBounds().getWidth();
}
 
Example 30
Project: SOEN6471-FreeCol   File: FreeColToolTipUI.java   View Source Code Vote up 5 votes
public void paint(Graphics g, JComponent c) {
   if (c.isOpaque()) {
       ImageLibrary.drawTiledImage("background.FreeColToolTip", g, c, null);
   }

   // TODO: find out why this is necessary
   g.setColor(Color.BLACK);
   Graphics2D graphics = (Graphics2D) g;

   float x = margin;
   float y = margin;
   for (String line : lineBreak.split(((JToolTip) c).getTipText())) {
       AttributedCharacterIterator styledText =
           new AttributedString(line).getIterator();

       LineBreakMeasurer measurer = new LineBreakMeasurer(styledText, frc);

       while (measurer.getPosition() < styledText.getEndIndex()) {

           TextLayout layout = measurer.nextLayout(maximumWidth);

           y += (layout.getAscent());
           float dx = layout.isLeftToRight() ?
               0 : (maximumWidth - layout.getAdvance());

           layout.draw(graphics, x + dx, y);
           y += layout.getDescent() + layout.getLeading();
       }
   }
}
 
Example 31
Project: pdfxtk   File: TextArea.java   View Source Code Vote up 5 votes
void rescale(double scale) {
     Rectangle bounds = getBounds(scale);

     HashMap settings = new HashMap();
     settings.put(TextAttribute.FONT, new Font(style.getFontAttributes(scale)));
     
     AttributedCharacterIterator par = (new AttributedString(element.getAttribute("text"), settings)).getIterator();
     LineBreakMeasurer lbm = new LineBreakMeasurer(par, new FontRenderContext(null, false, false));
     
     ArrayList drawList = new ArrayList();
     
     int parEnd   = par.getEndIndex();
     
     int positionX;
     int positionY = bounds.y;
     lbm.setPosition(par.getBeginIndex());
     while (lbm.getPosition() < parEnd) {
TextLayout layout = lbm.nextLayout(bounds.width);
positionX = bounds.x;
if (!layout.isLeftToRight()) {
  positionX += bounds.width - (int) layout.getAdvance();
}
positionY += layout.getAscent();
if (positionY > bounds.y+bounds.height) break;
drawList.add(new Point(positionX, positionY));
drawList.add(layout);
positionY += layout.getDescent() + layout.getLeading();
     }
     
     textPositions = new Point[drawList.size()/2];
     textLines     = new TextLayout[drawList.size()/2];
     textScale     = scale;

     for (int i = 0; i < textPositions.length; i++) {
textPositions[i] = (Point)      drawList.get(i*2);
textLines[i]     = (TextLayout) drawList.get(i*2+1);
     }
   }
 
Example 32
Project: pdfxtk   File: TextArea.java   View Source Code Vote up 5 votes
void rescale(double scale) {
     Rectangle bounds = getBounds(scale);

     HashMap settings = new HashMap();
     settings.put(TextAttribute.FONT, new Font(style.getFontAttributes(scale * Integer.parseInt(element.getAttribute("size")))));
     
     AttributedCharacterIterator par = (new AttributedString(element.getAttribute("text"), settings)).getIterator();
     LineBreakMeasurer lbm = new LineBreakMeasurer(par, new FontRenderContext(null, false, false));
     
     ArrayList drawList = new ArrayList();
     
     int parEnd   = par.getEndIndex();
     
     int positionX;
     int positionY = bounds.y;
     lbm.setPosition(par.getBeginIndex());
     while (lbm.getPosition() < parEnd) {
TextLayout layout = lbm.nextLayout(bounds.width);
positionX = bounds.x;
if (!layout.isLeftToRight()) {
  positionX += bounds.width - (int) layout.getAdvance();
}
positionY += layout.getAscent();
if (positionY > bounds.y+bounds.height) break;
drawList.add(new Point(positionX, positionY));
drawList.add(layout);
positionY += layout.getDescent() + layout.getLeading();
     }
     
     textPositions = new Point[drawList.size()/2];
     textLines     = new TextLayout[drawList.size()/2];
     textScale     = scale;

     for (int i = 0; i < textPositions.length; i++) {
textPositions[i] = (Point)      drawList.get(i*2);
textLines[i]     = (TextLayout) drawList.get(i*2+1);
     }
   }
 
Example 33
Project: litiengine   File: SpeechBubble.java   View Source Code Vote up 4 votes
private void createBubbleImage() {

    final BufferedImage img = ImageProcessing.getCompatibleImage(500, 500);
    final Graphics2D g = img.createGraphics();
    g.setFont(this.font);
    final int stringWidth = g.getFontMetrics().stringWidth(this.currentText);
    if (stringWidth < this.textBoxWidth) {
      this.textBoxWidth = stringWidth;
    }

    final FontRenderContext frc = g.getFontRenderContext();
    final AttributedString styledText = new AttributedString(this.currentText);
    styledText.addAttribute(TextAttribute.FONT, this.font);
    final AttributedCharacterIterator iterator = styledText.getIterator();
    final LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);
    measurer.setPosition(0);
    float y = 0;
    while (measurer.getPosition() < this.currentText.length()) {
      final TextLayout layout = measurer.nextLayout(this.textBoxWidth);
      y += layout.getAscent() + layout.getLeading() + 0.2;
    }

    final RoundRectangle2D bounds = new RoundRectangle2D.Double(0, 0, this.textBoxWidth + 2 * PADDING, y + 2 * PADDING, PADDING, PADDING);

    // Build a path
    final GeneralPath path = new GeneralPath();
    path.moveTo(bounds.getWidth() / 2.0 - TRIANGLE_SIZE / 2.0, bounds.getHeight());
    path.lineTo(bounds.getWidth() / 2.0, bounds.getHeight() + TRIANGLE_SIZE);
    path.lineTo(bounds.getWidth() / 2.0 + TRIANGLE_SIZE / 2.0, bounds.getHeight());
    path.closePath();

    final Area ar = new Area(bounds);
    ar.add(new Area(path));

    int width = ar.getBounds().width;
    this.height = ar.getBounds().height;
    g.setColor(SPEAK_BACKGROUNDCOLOR);
    g.fill(ar);

    g.setColor(SPEAK_BORDERCOLOR);
    g.draw(ar);
    g.dispose();

    this.bubble = ImageProcessing.crop(img, ImageProcessing.CROP_ALIGN_LEFT, ImageProcessing.CROP_VALIGN_TOP, width + 1, this.height + 1);
  }
 
Example 34
Project: pumpernickel   File: TextBoxInstruction.java   View Source Code Vote up 4 votes
/** Renders this text box. */
public void paint(Graphics2D g)
{
	g = (Graphics2D)g.create();
	g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
	g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
	g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);

	if(clipping!=null)
		g.clip(clipping);
	g.transform(transform);
	g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,opacity));
	
	text.setIndex(startingIndex);
	
	if(background!=null) {
		g.setColor(background);
		g.fill(box);
	}
	if(frame!=null && frameThickness>0) {
		g.setColor(frame);
		g.setStroke(new BasicStroke(frameThickness));
		g.draw(box);
	}
	
	g.clip(box);
	
	FontRenderContext frc = g.getFontRenderContext();
	frc = new FontRenderContext(new AffineTransform(), frc.isAntiAliased(), frc.usesFractionalMetrics());
	LineBreakMeasurer lbm = new LineBreakMeasurer(text,frc);
	float y = (float)box.getY()+insets.top+frameThickness/2f;
	while(lbm.getPosition()<text.getEndIndex()) {
		float lineWidth = this.maxWidth-frameThickness/2-insets.left-insets.right;
		TextLayout tl = lbm.nextLayout(lineWidth);
		
		float width = tl.getAdvance();
		y += tl.getAscent()-tl.getDescent();
		float x = (float)box.getCenterX()-width/2;
		tl.draw(g, x, y);
		y += tl.getDescent()+tl.getLeading();
		if(y>box.getHeight()+box.getY())
			return; //don't fuss about data that isn't visible
	}
}
 
Example 35
Project: flowable-engine   File: DefaultCaseDiagramCanvas.java   View Source Code Vote up 4 votes
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 36
Project: AudioProcessingBox   File: JSoundCapture.java   View Source Code Vote up 4 votes
public void paint(Graphics g) {

			Dimension d = getSize();
			int w = d.width;
			int h = d.height;
			int INFOPAD = 15;

			Graphics2D g2 = (Graphics2D) g;
			g2.setBackground(getBackground());
			g2.clearRect(0, 0, w, h);
			g2.setColor(Color.white);
			g2.fillRect(0, h - INFOPAD, w, INFOPAD);

			if (errStr != null) {
				g2.setColor(jfcBlue);
				g2.setFont(new Font("serif", Font.BOLD, 18));
				g2.drawString("ERROR", 5, 20);
				AttributedString as = new AttributedString(errStr);
				as.addAttribute(TextAttribute.FONT, font12, 0, errStr.length());
				AttributedCharacterIterator aci = as.getIterator();
				FontRenderContext frc = g2.getFontRenderContext();
				LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
				float x = 5, y = 25;
				lbm.setPosition(0);
				while (lbm.getPosition() < errStr.length()) {
					TextLayout tl = lbm.nextLayout(w - x - 5);
					if (!tl.isLeftToRight()) {
						x = w - tl.getAdvance();
					}
					tl.draw(g2, x, y += tl.getAscent());
					y += tl.getDescent() + tl.getLeading();
				}
			}
			else if (capture.thread != null) {
				// paint during capture
				g2.setColor(Color.black);
				g2.setFont(font12);
				g2.drawString("Length: " + String.valueOf(seconds), 3, h - 4);
			}
			else {
				// paint during playback
				g2.setColor(Color.black);
				g2.setFont(font12);
				g2.drawString("Length: " + String.valueOf(duration) + "    Position: " + String.valueOf(seconds), 3, h - 4);

				if (audioInputStream != null) {
					// .. render sampling graph ..
					g2.setColor(jfcBlue);
					for (int i = 1; i < lines.size(); i++) {
						g2.draw((Line2D) lines.get(i));
					}

					// .. draw current position ..
					if (seconds != 0) {
						double loc = seconds / duration * w;
						g2.setColor(pink);
						g2.setStroke(new BasicStroke(3));
						g2.draw(new Line2D.Double(loc, 0, loc, h - INFOPAD - 2));
					}
				}
			}
		}
 
Example 37
Project: SpeechRecognitionHMM   File: JSoundCapture.java   View Source Code Vote up 4 votes
public void paint(Graphics g) {

			Dimension d = getSize();
			int w = d.width;
			int h = d.height;
			int INFOPAD = 15;

			Graphics2D g2 = (Graphics2D) g;
			g2.setBackground(getBackground());
			g2.clearRect(0, 0, w, h);
			g2.setColor(Color.white);
			g2.fillRect(0, h - INFOPAD, w, INFOPAD);

			if (errStr != null) {
				g2.setColor(jfcBlue);
				g2.setFont(new Font("serif", Font.BOLD, 18));
				g2.drawString("ERROR", 5, 20);
				AttributedString as = new AttributedString(errStr);
				as.addAttribute(TextAttribute.FONT, font12, 0, errStr.length());
				AttributedCharacterIterator aci = as.getIterator();
				FontRenderContext frc = g2.getFontRenderContext();
				LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
				float x = 5, y = 25;
				lbm.setPosition(0);
				while (lbm.getPosition() < errStr.length()) {
					TextLayout tl = lbm.nextLayout(w - x - 5);
					if (!tl.isLeftToRight()) {
						x = w - tl.getAdvance();
					}
					tl.draw(g2, x, y += tl.getAscent());
					y += tl.getDescent() + tl.getLeading();
				}
			}
			else if (capture.thread != null) {
				// paint during capture
				g2.setColor(Color.black);
				g2.setFont(font12);
				g2.drawString("Length: " + String.valueOf(seconds), 3, h - 4);
			}
			else {
				// paint during playback
				g2.setColor(Color.black);
				g2.setFont(font12);
				g2.drawString("Length: " + String.valueOf(duration) + "    Position: " + String.valueOf(seconds), 3, h - 4);

				if (audioInputStream != null) {
					// .. render sampling graph ..
					g2.setColor(jfcBlue);
					for (int i = 1; i < lines.size(); i++) {
						g2.draw((Line2D) lines.get(i));
					}

					// .. draw current position ..
					if (seconds != 0) {
						double loc = seconds / duration * w;
						g2.setColor(pink);
						g2.setStroke(new BasicStroke(3));
						g2.draw(new Line2D.Double(loc, 0, loc, h - INFOPAD - 2));
					}
				}
			}
		}
 
Example 38
Project: ArasuiteIta   File: TRecordSound.java   View Source Code Vote up 4 votes
public void paint(Graphics g) {

            Dimension d = getSize();
            int w = d.width;
            int h = d.height;
            int INFOPAD = 15;

            Graphics2D g2 = (Graphics2D) g;
            g2.setBackground(getBackground());
            g2.clearRect(0, 0, w, h);
            g2.setColor(Color.white);
            g2.fillRect(0, h-INFOPAD, w, INFOPAD);

            if (errStr != null) {
                g2.setColor(jfcBlue);
                g2.setFont(new Font("serif", Font.BOLD, 18));
                g2.drawString("ERROR", 5, 20);
                AttributedString as = new AttributedString(errStr);
                as.addAttribute(TextAttribute.FONT, font12, 0, errStr.length());
                AttributedCharacterIterator aci = as.getIterator();
                FontRenderContext frc = g2.getFontRenderContext();
                LineBreakMeasurer lbm = new LineBreakMeasurer(aci, frc);
                float x = 5, y = 25;
                lbm.setPosition(0);
                while (lbm.getPosition() < errStr.length()) {
                    TextLayout tl = lbm.nextLayout(w-x-5);
                    if (!tl.isLeftToRight()) {
                        x = w - tl.getAdvance();
                    }
                    tl.draw(g2, x, y += tl.getAscent());
                    y += tl.getDescent() + tl.getLeading();
                }
            } else if (capture.thread != null) {
                g2.setColor(Color.black);
                g2.setFont(font12);
                g2.drawString("Length: " + String.valueOf(seconds), 3, h-4);
            } else {
                g2.setColor(Color.black);
                g2.setFont(font12);
                g2.drawString("File: " + fileName + "  Length: " + String.valueOf(duration) + "  Position: " + String.valueOf(seconds), 3, h-4);

                if (audioInputStream != null) {
                    // .. render sampling graph ..
                    g2.setColor(jfcBlue);
                    for (int i = 1; i < lines.size(); i++) {
                        g2.draw((Line2D) lines.get(i));
                    }

                    // .. draw current position ..
                    if (seconds != 0) {
                        double loc = seconds/duration*w;
                        g2.setColor(pink);
                        g2.setStroke(new BasicStroke(3));
                        g2.draw(new Line2D.Double(loc, 0, loc, h-INFOPAD-2));
                    }
                }
            }
        }
 
Example 39
Project: myjavacode   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 40
Project: myjavacode   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 41
Project: myjavacode   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 42
Project: myjavacode   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 43
Project: myjavacode   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 44
Project: myjavacode   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 45
Project: myjavacode   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 46
Project: activiti-in-action-codes   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 47
Project: activiti-in-action-codes   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 48
Project: activiti-in-action-codes   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 49
Project: praisenter   File: TextRenderer.java   View Source Code Vote up 4 votes
/**
 * Returns the bounds of the given text laid out as a paragraph with a maximum width.
 * <p>
 * This method will break on new line characters specified by {@link TextRenderer#LINE_SEPARATOR}.
 * @param text the string
 * @param font the font
 * @param fontRenderContext the font rendering context
 * @param width the maximum width
 * @param height the height of the text area; the text is not bounded by this
 * @return {@link TextBounds}
 */
public static final TextBounds getParagraphBounds(String text, Font font, FontRenderContext fontRenderContext, float width, float height) {
	// create an attributed string and assign the font
	AttributedString as = new AttributedString(text);
	as.addAttribute(TextAttribute.FONT, font);
	// get the character iterator
	AttributedCharacterIterator it = as.getIterator();
	// create a line break measurer to measure out lines
	LineBreakMeasurer measurer = new LineBreakMeasurer(it, fontRenderContext);
    
	// compute the height by laying out the lines
    float h = 0;
    float w = 0;
    float lh = 0;
    boolean isLastLayoutNewLine = false;
    while (measurer.getPosition() < text.length()) {
    	// get the expected ending character for this line
    	int bindex = measurer.getPosition();
    	int offset = measurer.nextOffset(width);
    	boolean isTerminatedByNewLine = false;
    	// see if there are any line break characters in this line
    	int index = text.indexOf(TextRenderer.LINE_SEPARATOR, bindex);
    	if (index >= 0) {
    		offset = index;
    		isTerminatedByNewLine = true;
    	}
    	TextLayout layout;
    	// check the offset against the beginning index
    	if (offset == bindex && isTerminatedByNewLine) {
    		measurer.setPosition(bindex + 1);
    		if (isLastLayoutNewLine) {
	    		// this will happen if a new line is found and the last
    			// line was terminated by a new line
	    		layout = new TextLayout(" ", font, fontRenderContext);
	    		isLastLayoutNewLine = true;
    		} else {
    			isLastLayoutNewLine = true;
    			// dont put anything into the layout just yet
    			continue;
    		}
    	} else {
    		// get the whole line as measured
    		layout = measurer.nextLayout(width, offset, false);
    		isLastLayoutNewLine = false;
    	}
    	// accumulate this lines height
    	h += layout.getAscent() + layout.getDescent() + layout.getLeading();
    	// keep the maximum width
    	float tw = layout.getAdvance();
    	w = w < tw ? tw : w;
    	// keep the line height
    	if (lh <= 0) {
    		lh = layout.getAscent() + layout.getDescent();
    	}
    }
    
    // return the bounds
    return new TextBounds(width, height, w, h, lh);
}
 
Example 50
Project: activiti-in-action-codes   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 51
Project: activiti-in-action-codes   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 52
Project: magarena   File: OracleText.java   View Source Code Vote up 4 votes
private static SortedMap<Float, TextLayout> tryTextLayout(
    AttributedString attrString,
    FontRenderContext frc,
    Rectangle box,
    int leftPadding,
    int topPadding
) {
    final SortedMap<Float, TextLayout> lines = new TreeMap<>();
    AttributedCharacterIterator text = attrString.getIterator();
    int paragraphStart = text.getBeginIndex();
    int paragraphEnd = text.getEndIndex();
    LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(text, frc);
    float boxWidth = (float)box.getWidth();
    float boxHeight = (float)box.getHeight();
    float posY = topPadding;
    lineMeasurer.setPosition(paragraphStart);

    //Measure length of string to fit in box
    final AttributedCharacterIterator iter = attrString.getIterator();
    while (lineMeasurer.getPosition() < paragraphEnd) {
        //Check for ptPanel overlap
        int next = lineMeasurer.nextOffset(posY >= 123 ? boxWidth - (leftPadding << 1) - 100 : boxWidth - (leftPadding << 1));
        int limit = next;
        //Check for newlines
        for (int i = lineMeasurer.getPosition(); i < next; ++i) {
            char c = iter.setIndex(i);
            if (c == NEWLINE && i > lineMeasurer.getPosition()) {
                limit = i;
                break;
            }
        }

        //get+draw measured length
        TextLayout layout = lineMeasurer.nextLayout(boxWidth, limit, false);
        posY += layout.getAscent();
        lines.put(posY, layout);

        //add extra space between paragraphs
        if (limit < next) {
            posY += layout.getLeading() + layout.getDescent();
        }

        //move to next line
        posY += layout.getDescent();

        //check if out of room
        if (posY > boxHeight) {
            lines.clear();
            break;
        }
    }
    return lines;
}
 
Example 53
Project: colormap-explorer   File: OverlayExamplePanel.java   View Source Code Vote up 4 votes
@Override
protected void paintComponent(Graphics g1)
{
	super.paintComponent(g1);
	Graphics2D g = (Graphics2D)g1;

	Font derivedFont = g.getFont().deriveFont(Font.PLAIN, fontSize);

	Random r = new Random(123456);
	int gridX = 20;
	int gridY = 20;

	int width = IntMath.divide(getWidth(), gridX, RoundingMode.CEILING);
	int height = IntMath.divide(getHeight(), gridY, RoundingMode.CEILING);

	BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

	for (int y = 0; y < height; y++)
	{
		for (int x = 0; x < width; x++)
		{
			double cx = r.nextDouble();
			double cy = r.nextDouble();

			Color color = colormap.getColor(cx, cy);

			img.setRGB(x, y, color.getRGB());
		}
	}

	// width * gridX is not identical with getWidt() due to rounding

	g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
	g.drawImage(img, 0, 0, width * gridX, height * gridY, null);

	FontRenderContext frc = g.getFontRenderContext();

	String text = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt "
			+ "ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo "
			+ "dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. ";

	AttributedString attributedString = new AttributedString(text);
	attributedString.addAttribute(TextAttribute.FONT, derivedFont);
	AttributedCharacterIterator iterator = attributedString.getIterator();
	LineBreakMeasurer measurer = new LineBreakMeasurer(iterator, frc);

	g.setColor(overlayColor);

	float tx = 2;	// add some tiny distance offset to the top/left corner
       float ty = 2;
       while (measurer.getPosition() < iterator.getEndIndex())
       {
           TextLayout layout = measurer.nextLayout(getWidth());

           ty += layout.getAscent();
           float dx = 0;

           layout.draw(g, tx + dx, ty);
           ty += layout.getDescent() + layout.getLeading();
       }
}
 
Example 54
Project: birt   File: StyleManagerUtils.java   View Source Code Vote up 4 votes
/**
 * Calculate the height of a string formatted according to a set of RichTextRuns and fitted within a give width.
 * @param sourceText
 * The string to be measured.
 * @param defaultFont
 * The font to be used prior to the first RichTextRun.
 * @param widthMM
 * The width of the output.
 * @param richTextRuns
 * The list of RichTextRuns to be applied to the string
 * @return
 * The heigh, in points, of a box big enough to contain the formatted sourceText.
 */
public float calculateTextHeightPoints( String sourceText, Font defaultFont, double widthMM, List< RichTextRun> richTextRuns ) {
	log.debug( "Calculating height for ", sourceText);
	
	final float widthPt = (float)(72 * Math.max( 0, widthMM - 6 ) / 25.4); 
	
	float totalHeight = 0;
	String[] textLines = sourceText.split("\n");
	int lineStartIndex = 0;
	String lastLine = null;
	Font font = defaultFont;
	for( String textLine : textLines ) {
		if( lastLine != null ) {
			lineStartIndex += lastLine.length() + 1;
		} 
		lastLine = textLine;
		
		AttributedString attrString = new AttributedString(textLine.isEmpty() ? " " : textLine);
		int runEnd = textLine.length();
		
		int richTextRunIndex = getRichTextRunIndexForStart(richTextRuns, lineStartIndex);
		if( richTextRunIndex >= 0 ) {
			font = richTextRuns.get(richTextRunIndex).font;
			if( ( richTextRunIndex < richTextRuns.size() - 1 ) && ( richTextRuns.get(richTextRunIndex + 1).startIndex < runEnd ) ) {
				runEnd = richTextRuns.get(richTextRunIndex + 1).startIndex;
			}
		}
		
		log.debug( "Adding attribute - [", 0, " - ", runEnd, "] = ", defaultFont.getFontName(), " ", defaultFont.getFontHeightInPoints(), "pt" );
		addFontAttributes(attrString, font, 0, textLine.isEmpty() ? 1 : runEnd );

		for( ++richTextRunIndex; ( richTextRunIndex < richTextRuns.size() ) && ( richTextRuns.get( richTextRunIndex ).startIndex < lineStartIndex + textLine.length() ) ; ++richTextRunIndex ) {
			RichTextRun run = richTextRuns.get( richTextRunIndex );
			RichTextRun nextRun = richTextRunIndex < richTextRuns.size() - 1 ? richTextRuns.get( richTextRunIndex + 1) : null;
			if( ( run.startIndex >= lineStartIndex ) && ( run.startIndex < lineStartIndex + textLine.length() + 1 ) ) {
				int startIdx = run.startIndex - lineStartIndex;
				int endIdx = ( nextRun == null ? sourceText.length() : nextRun.startIndex ) - lineStartIndex;
				if( endIdx > textLine.length() ) {
					endIdx = textLine.length();
				}
				if( startIdx < endIdx ) {
					log.debug( "Adding attribute: [", startIdx, " - ", endIdx, "] = ", run.font.getFontName(), " ", run.font.getFontHeightInPoints(), "pt" );
					addFontAttributes(attrString, run.font, startIdx, endIdx );
				}
			}
		}		
		
		LineBreakMeasurer measurer = new LineBreakMeasurer( attrString.getIterator(), frc);
	    
		float heightAdjustment = 0.0F;
		int lineLength = textLine.isEmpty() ? 1 : textLine.length();
		while (measurer.getPosition() < lineLength) {
	         TextLayout layout = measurer.nextLayout( widthPt );
	         float lineHeight = layout.getAscent() + layout.getDescent() + layout.getLeading();
	         if( layout.getDescent() + layout.getLeading() > heightAdjustment ) {
	        	 heightAdjustment = layout.getDescent() + layout.getLeading();
	         }
	         log.debug ( "Line: ", textLine, " gives height ", lineHeight, "(", layout.getAscent(), "/", layout.getDescent(), "/", layout.getLeading(), ")");
	         totalHeight += lineHeight;
		}
		totalHeight += heightAdjustment;
		
	}
	log.debug( "Height calculated as ", totalHeight );
	return totalHeight;
}
 
Example 55
Project: jenkins-inheritance-plugin   File: SVGText.java   View Source Code Vote up 4 votes
protected Collection<String> getBrokenLine(String line) {
	initFontMetrics();
	
	LinkedList<String> out = new LinkedList<String>();
	if (line == null || line.isEmpty()) {
		return out;
	}
	
	//Assigning correct font
	Map<Attribute, Object> attributes = new HashMap<Attribute, Object>();
	attributes.put(TextAttribute.FONT, g.getFont());
	
	//Creating text with the above attributes
	AttributedString as = new AttributedString(line, attributes);
	AttributedCharacterIterator aci = as.getIterator();
	LineBreakMeasurer measurer = new LineBreakMeasurer(
			aci, this.g.getFontRenderContext()
	);
	
	
	int start = 0;
	while (true) {
		TextLayout tl = measurer.nextLayout((float)lineBreakPxls);
		if (start >= line.length() || tl == null) {
			if (start < line.length()) {
				out.add(line.substring(start, line.length()));
			}
			break;
		}
		int end = measurer.getPosition();
		String text = line.substring(start, end);
		
		float lenInPx = tl.getAdvance();
		if (lenInPx > lineBreakPxls) {
			Log.error(String.format(
					"Line breaker error: String '%s' is %fpx wide, but should be < %fpx",
					text, lenInPx, lineBreakPxls
			));
		}
		out.add(text);
		start = end;
	}
	
	return out;
}
 
Example 56
Project: xbpm5   File: ProcessDiagramCanvas.java   View Source Code Vote up 4 votes
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 + ((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 57
Project: pdfxtk   File: TextArea2.java   View Source Code Vote up 4 votes
void rescale(double scale) {
     Rectangle bounds = getBounds(scale);

     HashMap settings = new HashMap();
     
     // java 5: Float fontSize = Float.parseFloat(element.getAttribute("font-size"));
     float fontSize = Float.parseFloat(element.getAttribute("font-size"));
     
     settings.put(TextAttribute.FONT, new Font(style.getFontAttributes(scale * fontSize)));
     
     AttributedCharacterIterator par = (new AttributedString(element.getAttribute("text"), settings)).getIterator();
     
     //style.fontSize = Float.parseFloat(element.getAttribute("font-size"));
     //style.setParam(context, this, element.getAttribute("font-size"));
    // this.style("fontsize", element.getAttribute("font-size"));
     
     LineBreakMeasurer lbm = new LineBreakMeasurer(par, new FontRenderContext(null, false, false));
     
     ArrayList drawList = new ArrayList();
     
     int parEnd   = par.getEndIndex();
     
     int positionX;
     int positionY = bounds.y;
     lbm.setPosition(par.getBeginIndex());
     while (lbm.getPosition() < parEnd) {
TextLayout layout = lbm.nextLayout(bounds.width);
positionX = bounds.x;
if (!layout.isLeftToRight()) {
  positionX += bounds.width - (int) layout.getAdvance();
}
positionY += layout.getAscent();
if (positionY > bounds.y+bounds.height) break;
drawList.add(new Point(positionX, positionY));
drawList.add(layout);
positionY += layout.getDescent() + layout.getLeading();
     }
     
     textPositions = new Point[drawList.size()/2];
     textLines     = new TextLayout[drawList.size()/2];
     textScale     = scale;

     for (int i = 0; i < textPositions.length; i++) {
textPositions[i] = (Point)      drawList.get(i*2);
textLines[i]     = (TextLayout) drawList.get(i*2+1);
     }
   }
 
Example 58
Project: PhET   File: PText.java   View Source Code Vote up 2 votes
/**
 * Compute the next layout using the specified line break measurer,
 * available width, and next line break offset.
 * 
 * @param lineBreakMeasurer line break measurer
 * @param availableWidth available width
 * @param nextLineBreakOffset next line break offset
 * @return the next layout computed using the specified line break measurer,
 *         available width, and next line break offset
 */
protected TextLayout computeNextLayout(final LineBreakMeasurer lineBreakMeasurer, final float availableWidth,
        final int nextLineBreakOffset) {
    return lineBreakMeasurer.nextLayout(availableWidth, nextLineBreakOffset, false);
}
 
Example 59
Project: piccolo2d.java   File: PText.java   View Source Code Vote up 2 votes
/**
 * Compute the next layout using the specified line break measurer,
 * available width, and next line break offset.
 * 
 * @param lineBreakMeasurer line break measurer
 * @param availableWidth available width
 * @param nextLineBreakOffset next line break offset
 * @return the next layout computed using the specified line break measurer,
 *         available width, and next line break offset
 */
protected TextLayout computeNextLayout(final LineBreakMeasurer lineBreakMeasurer, final float availableWidth,
        final int nextLineBreakOffset) {
    return lineBreakMeasurer.nextLayout(availableWidth, nextLineBreakOffset, false);
}