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

The following are Jave code examples for showing how to use setPosition() 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.
Example 1
Project: tribaltrouble   File: Test.java   Source Code and License 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 2
Project: jrunalyzer   File: SelectedWaypointRenderer.java   Source Code and License 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 3
Project: Harmonia-1.5   File: MessageController.java   Source Code and License 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 4
Project: litiengine   File: SpeechBubble.java   Source Code and License 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 5
Project: openjdk-jdk10   File: TestLineBreakWithFontSub.java   Source Code and License 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 6
Project: DigitalMediaServer   File: SwingUtils.java   Source Code and License 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 7
Project: jdk8u_jdk   File: TestLineBreakWithFontSub.java   Source Code and License 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 8
Project: firebird-vizualization-tool   File: MultilineLayouter.java   Source Code and License 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 9
Project: pdfxtk   File: TextArea.java   Source Code and License 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 10
Project: pdfxtk   File: TextArea.java   Source Code and License 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 11
Project: litiengine   File: SpeechBubble.java   Source Code and License 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 12
Project: pumpernickel   File: FixedWidthTextArea.java   Source Code and License Vote up 4 votes
@Override
public Dimension getPreferredSize() {
	if(cachedSize==null) {
		Map<Attribute, Object> attributes = new HashMap<>();
		attributes.put( TextAttribute.FONT, getFont());
		String text = getText();
		
		/** It is crucial this be accurate!  I used to have it
		 * always true/true, and XP sometimes failed because of it.
		 */
		FontRenderContext frc = isMac ? 
				new FontRenderContext(new AffineTransform(),true,true) :
					new FontRenderContext(new AffineTransform(),false,false);
				
		String[] paragraphs = getParagraphs(text);
		int rows = 0;
		for(int a = 0; a<paragraphs.length; a++) {
			int textLength = paragraphs[a].length();
			if(isWhiteSpace(paragraphs[a])) {
				rows++;
			} else {
				AttributedString attrString = new AttributedString( paragraphs[a], attributes);

				LineBreakMeasurer lbm = new LineBreakMeasurer(attrString.getIterator(),frc);
			
				int pos = 0;
				while(pos<textLength) {
					pos = lbm.nextOffset(fixedWidth);
					lbm.setPosition(pos);
					rows++;
				}
			}
		}
		int extra = 0;
		if(isXP) { //allow for descents
			extra = (int)(getFont().getLineMetrics("g", frc).getDescent()+1);
		}
		cachedSize = new Dimension(fixedWidth, rows*getRowHeight()+extra);
	}
	return new Dimension(cachedSize);
}
 
Example 13
Project: pumpernickel   File: TextSize.java   Source Code and License Vote up 4 votes
public static Dimension getPreferredSize(JTextArea textArea,int preferredWidth) {
	Font font = textArea.getFont();
	String text = textArea.getText();
	
	Map<Attribute, Object> attributes = new HashMap<Attribute, Object>();
	attributes.put( TextAttribute.FONT, font);
	
	/** It is crucial this be accurate!  I used to have it
	 * always true/true, and XP sometimes failed because of it.
	 */
	Graphics2D g = ((Graphics2D)textArea.getGraphics());
	FontRenderContext frc = null;
	if(g!=null) frc = g.getFontRenderContext();
	
	if(frc==null) {
		//on Mac "true, false" seemed to be the right combo.
		//try testing with QOptionPaneDemo in French and see the
		//external changes dialog
		frc = new FontRenderContext( null, true, false);
	}
	
	String[] paragraphs = Text.getParagraphs(text);
	int rows = 0;
	for(int a = 0; a<paragraphs.length; a++) {
		int textLength = paragraphs[a].length();
		if(Text.isWhiteSpace(paragraphs[a])) {
			rows++;
		} else {
			AttributedString attrString = new AttributedString( paragraphs[a], attributes);

			LineBreakMeasurer lbm = new LineBreakMeasurer(attrString.getIterator(),frc);
		
			int pos = 0;
			while(pos<textLength) {
				pos = lbm.nextOffset(preferredWidth);
				lbm.setPosition(pos);
				rows++;
			}
		}
	}
	int extra = 0;
	if(JVM.isWindowsXP) { //allow for descents
		extra = (int)(font.getLineMetrics("g", frc).getDescent()+1);
	}

       FontMetrics metrics = textArea.getFontMetrics(font);
	int rowHeight = metrics.getHeight();
       
	return new Dimension(preferredWidth, rows*rowHeight+extra);
}
 
Example 14
Project: AudioProcessingBox   File: JSoundCapture.java   Source Code and License 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 15
Project: SpeechRecognitionHMM   File: JSoundCapture.java   Source Code and License 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 16
Project: ArasuiteIta   File: TRecordSound.java   Source Code and License 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 17
Project: praisenter   File: TextRenderer.java   Source Code and License 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 18
Project: magarena   File: OracleText.java   Source Code and License 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 19
Project: XPressOnTechnologies   File: RGPTUtil.java   Source Code and License Vote up 4 votes
public static int getText4BBox(Graphics2D g2d, String text, int startPos,
		double width, Hashtable fontAttrib, Boolean isParaSelection) {

	AttributedString textString = new AttributedString(text, fontAttrib);
	AttributedCharacterIterator charIter = textString.getIterator();
	int paragraphStart = charIter.getBeginIndex();
	int paragraphEnd = charIter.getEndIndex();
	LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIter,
			g2d.getFontRenderContext());

	// This Margin is provided to avoid text overlap. If 1.0 No Margin set.
	double margin = 1.0;
	double formatWidth = width * margin;

	// Get line offset from lineMeasurer until the entire paragraph has been
	// displayed. This is added to UserSetValue to get the Exact Text during
	// PDF Generation
	int currPos = 0;
	String userSelText;
	if (startPos >= paragraphEnd)
		return -1;
	lineMeasurer.setPosition(startPos);
	while (lineMeasurer.getPosition() < paragraphEnd) {
		// Retrieve next layout.
		lineMeasurer.setPosition(startPos);
		currPos = lineMeasurer.nextOffset((float) formatWidth);
		// userSelText = vdpText.substring(startPos, currPos);
		System.out.println("Text Start: " + startPos + " :CurrPos: "
				+ currPos + " VDP Text Length: " + text.length());
		break;
	}

	// The New Lines are supported only when the VDP Text Mode is Para.
	if (!isParaSelection) {
		return currPos;
	}
	// Checking for New Line
	int charIndex = 0;
	for (char c = charIter.first(); c != charIter.DONE; c = charIter.next()) {
		charIndex = charIter.getIndex();
		if (charIndex <= startPos)
			continue;
		if (charIndex >= currPos) {
			return currPos;
		}
		if (c == '\n') {
			System.out
					.println("Found New Line at Char Index: " + charIndex);
			return charIndex;
		}
	}

	return currPos;
}
 
Example 20
Project: XPressOnTechnologies   File: PDFPersonalizationUtil.java   Source Code and License Vote up 4 votes
private int getVDPText4BBox(Graphics2D g2d, String vdpText,
		HashMap vdpData, int vdpTextMode, int startPos,
		Rectangle2D.Double rectBBox, Hashtable fontAttrib,
		Boolean isParaSelection) {
	// String vdpText = (String) vdpData.get("UserSetValue");
	AttributedString vdpTextString = new AttributedString(vdpText,
			fontAttrib);
	AttributedCharacterIterator charIter = vdpTextString.getIterator();
	int paragraphStart = charIter.getBeginIndex();
	int paragraphEnd = charIter.getEndIndex();
	LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(charIter,
			g2d.getFontRenderContext());

	// This Margin is provided to avoid text overlap. If 1.0 No Margin set.
	double margin = 1.0;
	double formatWidth = rectBBox.getWidth() * margin;

	// Get line offset from lineMeasurer until the entire paragraph has been
	// displayed. This is added to UserSetValue to get the Exact Text during
	// PDF Generation
	int currPos = 0;
	String userSelText;
	if (startPos >= paragraphEnd)
		return -1;
	lineMeasurer.setPosition(startPos);
	while (lineMeasurer.getPosition() < paragraphEnd) {
		// Retrieve next layout.
		lineMeasurer.setPosition(startPos);
		currPos = lineMeasurer.nextOffset((float) formatWidth);
		// userSelText = vdpText.substring(startPos, currPos);
		System.out.println("Text Start: " + startPos + " :CurrPos: "
				+ currPos + " VDP Text Length: " + vdpText.length());
		break;
	}

	// The New Lines are supported only when the VDP Text Mode is Para.
	if (!isParaSelection) {
		// if (currPos < vdpText.length()) {
		// System.out.println("Current pos: " + currPos + " is less " +
		// "then VDP Text Length: " + vdpText.length());
		// //currPos = vdpText.length()-1;
		// }
		return currPos;
	}
	// Checking for New Line
	int charIndex = 0;
	// lineMeasurer.setPosition(paragraphStart);
	for (char c = charIter.first(); c != charIter.DONE; c = charIter.next()) {
		charIndex = charIter.getIndex();
		if (charIndex <= startPos)
			continue;
		if (charIndex >= currPos) {
			return currPos;
		}
		if (c == '\n') {
			System.out
					.println("Found New Line at Char Index: " + charIndex);
			return charIndex;
		}
	}

	return currPos;
}
 
Example 21
Project: pdfxtk   File: TextArea2.java   Source Code and License 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);
     }
   }