Example usage for java.awt.font TextLayout TextLayout

List of usage examples for java.awt.font TextLayout TextLayout

Introduction

In this page you can find the example usage for java.awt.font TextLayout TextLayout.

Prototype

public TextLayout(AttributedCharacterIterator text, FontRenderContext frc) 

Source Link

Document

Constructs a TextLayout from an iterator over styled text.

Usage

From source file:Main.java

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    AttributedString astr = new AttributedString("aString");
    astr.addAttribute(TextAttribute.FONT, new Font("", 1, 30), 1, 2);
    astr.addAttribute(TextAttribute.BACKGROUND, Color.red, 2, 3);

    TextLayout tl = new TextLayout(astr.getIterator(), g2d.getFontRenderContext());
    tl.draw(g2d, 10, 20);//from   w  w w  .ja v a  2 s  . c o m
}

From source file:BasicShapes.java

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;

    int x = 10, y = 10, start = 2, end = 4;

    AttributedString astr = new AttributedString("aString");
    astr.addAttribute(TextAttribute.FONT, new Font("", 1, 1), start, end);
    astr.addAttribute(TextAttribute.BACKGROUND, Color.red, start, end);

    // Draw mixed-style text
    TextLayout tl = new TextLayout(astr.getIterator(), g2d.getFontRenderContext());
    tl.draw(g2d, x, y);/*from w w  w . ja  v  a 2  s . c om*/

}

From source file:HitTestSample.java

public HitTestSample() {
    AttributedCharacterIterator text = helloWorld.getIterator();
    // Create a new TextLayout from the given text.
    textLayout = new TextLayout(text, DEFAULT_FRC);

    // Initilize insertionIndex.
    insertionIndex = 0;//from w  w w . j av a2  s  .c  o  m

    addMouseListener(new HitTestMouseListener());
}

From source file:TextLayoutWithCarets.java

private void initialize(Graphics2D g2) {
    String s = "Java Source and Support.";
    // Create a plain and italic font.
    int fontSize = 32;
    Font font = new Font("Lucida Sans Regular", Font.PLAIN, fontSize);
    Font italicFont = new Font("Lucida Sans Oblique", Font.ITALIC, fontSize);
    // Create an Attributed String
    AttributedString as = new AttributedString(s);
    as.addAttribute(TextAttribute.FONT, font);
    as.addAttribute(TextAttribute.FONT, italicFont, 2, 5);
    // Get the iterator.
    AttributedCharacterIterator iterator = as.getIterator();
    // Create a TextLayout.
    FontRenderContext frc = g2.getFontRenderContext();
    mLayout = new TextLayout(iterator, frc);

    mHit = mLayout.getNextLeftHit(1);//from  w w  w . ja v a2 s.c om

    // Respond to left and right arrow keys.

    mInitialized = true;
}

From source file:AttributesApp.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;

    attribCharIterator = attribString.getIterator();

    FontRenderContext frc = new FontRenderContext(null, false, false);
    TextLayout layout = new TextLayout(attribCharIterator, frc);

    layout.draw(g2, 20, 100);//w w w .  j  a  v  a  2s. c  om
}

From source file:org.pentaho.reporting.engine.classic.core.layout.process.text.ComplexTextMinorAxisLayoutStep.java

private void addCompleteLine(final ParagraphRenderBox box, final ParagraphPoolBox lineBoxContainer,
        final StyleSheet layoutContext) {
    RichTextSpec richText = RichTextSpecProducer.compute(lineBoxContainer, metaData, resourceManager);

    final FontRenderContext fontRenderContext = createFontRenderContext(layoutContext);
    final TextLayout textLayout = new TextLayout(richText.createAttributedCharacterIterator(),
            fontRenderContext);/*w  w  w.ja v a2  s  .  c o  m*/
    double height = textLayout.getAscent() + textLayout.getDescent() + textLayout.getLeading();

    final RenderableComplexText text = richText.create(lineBoxContainer);
    text.setTextLayout(textLayout);
    ParagraphFontMetricsImpl metrics = new ParagraphFontMetricsImpl();
    metrics.update(textLayout);
    final RenderBox line = generateLine(box, lineBoxContainer, text, height, metrics);
    // and finally add the line to the paragraph
    getNodeContext().updateX2(line.getCachedX2());
    box.addGeneratedChild(line);
}

From source file:org.zkoss.poi.ss.util.SheetUtil.java

/**
 * Compute width of a single cell/*from w w  w  . j a va  2 s.c  o m*/
 *
 * @param cell the cell whose width is to be calculated
 * @param defaultCharWidth the width of a single character
 * @param formatter formatter used to prepare the text to be measured
 * @param useMergedCells    whether to use merged cells
 * @return  the width in pixels
 */
public static double getCellWidth(Cell cell, int defaultCharWidth, DataFormatter formatter,
        boolean useMergedCells) {

    Sheet sheet = cell.getSheet();
    Workbook wb = sheet.getWorkbook();
    Row row = cell.getRow();
    int column = cell.getColumnIndex();

    int colspan = 1;
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
        CellRangeAddress region = sheet.getMergedRegion(i);
        if (containsCell(region, row.getRowNum(), column)) {
            if (!useMergedCells) {
                // If we're not using merged cells, skip this one and move on to the next.
                return -1;
            }
            cell = row.getCell(region.getFirstColumn());
            colspan = 1 + region.getLastColumn() - region.getFirstColumn();
        }
    }

    CellStyle style = cell.getCellStyle();
    int cellType = cell.getCellType();

    // for formula cells we compute the cell width for the cached formula result
    if (cellType == Cell.CELL_TYPE_FORMULA)
        cellType = cell.getCachedFormulaResultType();

    Font font = wb.getFontAt(style.getFontIndex());

    AttributedString str;
    TextLayout layout;

    double width = -1;
    if (cellType == Cell.CELL_TYPE_STRING) {
        RichTextString rt = cell.getRichStringCellValue();
        String[] lines = rt.getString().split("\\n");
        for (int i = 0; i < lines.length; i++) {
            String txt = lines[i] + defaultChar;

            str = new AttributedString(txt);
            copyAttributes(font, str, 0, txt.length());

            if (rt.numFormattingRuns() > 0) {
                // TODO: support rich text fragments
            }

            layout = new TextLayout(str.getIterator(), fontRenderContext);
            if (style.getRotation() != 0) {
                /*
                 * Transform the text using a scale so that it's height is increased by a multiple of the leading,
                 * and then rotate the text before computing the bounds. The scale results in some whitespace around
                 * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
                 * is added by the standard Excel autosize.
                 */
                AffineTransform trans = new AffineTransform();
                trans.concatenate(
                        AffineTransform.getRotateInstance(style.getRotation() * 2.0 * Math.PI / 360.0));
                trans.concatenate(AffineTransform.getScaleInstance(1, fontHeightMultiple));
                width = Math.max(width,
                        ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth)
                                + cell.getCellStyle().getIndention());
            } else {
                width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth)
                        + cell.getCellStyle().getIndention());
            }
        }
    } else {
        String sval = null;
        if (cellType == Cell.CELL_TYPE_NUMERIC) {
            // Try to get it formatted to look the same as excel
            try {
                sval = formatter.formatCellValue(cell, dummyEvaluator);
            } catch (Exception e) {
                sval = String.valueOf(cell.getNumericCellValue());
            }
        } else if (cellType == Cell.CELL_TYPE_BOOLEAN) {
            sval = String.valueOf(cell.getBooleanCellValue()).toUpperCase();
        }
        if (sval != null) {
            String txt = sval + defaultChar;
            str = new AttributedString(txt);
            copyAttributes(font, str, 0, txt.length());

            layout = new TextLayout(str.getIterator(), fontRenderContext);
            if (style.getRotation() != 0) {
                /*
                 * Transform the text using a scale so that it's height is increased by a multiple of the leading,
                 * and then rotate the text before computing the bounds. The scale results in some whitespace around
                 * the unrotated top and bottom of the text that normally wouldn't be present if unscaled, but
                 * is added by the standard Excel autosize.
                 */
                AffineTransform trans = new AffineTransform();
                trans.concatenate(
                        AffineTransform.getRotateInstance(style.getRotation() * 2.0 * Math.PI / 360.0));
                trans.concatenate(AffineTransform.getScaleInstance(1, fontHeightMultiple));
                width = Math.max(width,
                        ((layout.getOutline(trans).getBounds().getWidth() / colspan) / defaultCharWidth)
                                + cell.getCellStyle().getIndention());
            } else {
                width = Math.max(width, ((layout.getBounds().getWidth() / colspan) / defaultCharWidth)
                        + cell.getCellStyle().getIndention());
            }
        }
    }
    return width;
}

From source file:org.zkoss.poi.ss.util.SheetUtil.java

/**
 * Compute width of a column and return the result
 *
 * @param sheet the sheet to calculate//w  ww  .j  av  a  2s  .c o  m
 * @param column    0-based index of the column
 * @param useMergedCells    whether to use merged cells
 * @return  the width in pixels
 */
public static double getColumnWidth(Sheet sheet, int column, boolean useMergedCells) {
    AttributedString str;
    TextLayout layout;

    Workbook wb = sheet.getWorkbook();
    DataFormatter formatter = new DataFormatter(ZssContext.getCurrent().getLocale(), false); //20111227, henrichen@zkoss.org
    Font defaultFont = wb.getFontAt((short) 0);

    str = new AttributedString(String.valueOf(defaultChar));
    copyAttributes(defaultFont, str, 0, 1);
    layout = new TextLayout(str.getIterator(), fontRenderContext);
    int defaultCharWidth = (int) layout.getAdvance();

    double width = -1;
    for (Row row : sheet) {
        Cell cell = row.getCell(column);

        if (cell == null) {
            continue;
        }

        double cellWidth = getCellWidth(cell, defaultCharWidth, formatter, useMergedCells);
        width = Math.max(width, cellWidth);
    }
    return width;
}

From source file:org.zkoss.poi.ss.util.SheetUtil.java

/**
 * Compute width of a column based on a subset of the rows and return the result
 *
 * @param sheet the sheet to calculate//from  w  w w .  ja  v a2 s .c o m
 * @param column    0-based index of the column
 * @param useMergedCells    whether to use merged cells
 * @param firstRow  0-based index of the first row to consider (inclusive)
 * @param lastRow   0-based index of the last row to consider (inclusive)
 * @return  the width in pixels
 */
public static double getColumnWidth(Sheet sheet, int column, boolean useMergedCells, int firstRow,
        int lastRow) {
    AttributedString str;
    TextLayout layout;

    Workbook wb = sheet.getWorkbook();
    DataFormatter formatter = new DataFormatter(ZssContext.getCurrent().getLocale(), false); //20111227, henrichen@zkoss.org: ZSS-68
    Font defaultFont = wb.getFontAt((short) 0);

    str = new AttributedString(String.valueOf(defaultChar));
    copyAttributes(defaultFont, str, 0, 1);
    layout = new TextLayout(str.getIterator(), fontRenderContext);
    int defaultCharWidth = (int) layout.getAdvance();

    double width = -1;
    for (int rowIdx = firstRow; rowIdx <= lastRow; ++rowIdx) {
        Row row = sheet.getRow(rowIdx);
        if (row != null) {

            Cell cell = row.getCell(column);

            if (cell == null) {
                continue;
            }

            double cellWidth = getCellWidth(cell, defaultCharWidth, formatter, useMergedCells);
            width = Math.max(width, cellWidth);
        }
    }
    return width;
}