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(String string, Map<? extends Attribute, ?> attributes, FontRenderContext frc) 

Source Link

Document

Constructs a TextLayout from a String and an attribute set.

Usage

From source file:net.fenyo.gnetwatch.GUI.BasicComponent.java

/**
 * Paints axis./*from w  ww.j av a 2  s . co m*/
 * @param none.
 * @return long current time displayed at the axis bottom.
 */
// AWT thread
private long paintAxis() {
    backing_g.setColor(new Color(50, 50, 50));
    backing_g.fillRect(axis_margin_left, axis_margin_top,
            dimension.width - axis_margin_left - axis_margin_right + 1,
            dimension.height - axis_margin_top - axis_margin_bottom + 1);

    backing_g.setColor(Color.YELLOW);
    backing_g.drawLine(axis_margin_left, dimension.height - axis_margin_bottom,
            dimension.width - axis_margin_right, dimension.height - axis_margin_bottom);
    backing_g.drawLine(axis_margin_left, axis_margin_top, axis_margin_left,
            dimension.height - axis_margin_bottom);

    backing_g.setColor(Color.YELLOW.darker());
    backing_g.drawLine(axis_margin_left + 1, axis_margin_top, dimension.width - axis_margin_right,
            axis_margin_top);
    backing_g.drawLine(dimension.width - axis_margin_right, axis_margin_top,
            dimension.width - axis_margin_right, dimension.height - axis_margin_bottom - 1);

    int vinterval_pos = dimension.height - axis_margin_bottom - pixels_per_vinterval;
    backing_g.setColor(Color.YELLOW.darker().darker().darker());
    while (vinterval_pos + 9 * (pixels_per_vinterval / 10) > axis_margin_top) {
        int cpt = 10;
        while (--cpt > 0)
            if (vinterval_pos + cpt * (pixels_per_vinterval / 10) > axis_margin_top)
                backing_g.drawLine(axis_margin_left + 1, vinterval_pos + cpt * (pixels_per_vinterval / 10),
                        dimension.width - axis_margin_right - 1,
                        vinterval_pos + cpt * (pixels_per_vinterval / 10));
        vinterval_pos -= pixels_per_vinterval;
    }

    final long now;
    if (manual_mode)
        now = manual_now;
    else
        now = System.currentTimeMillis();

    final long time_to_display = now - now % _getDelayPerInterval();
    final int pixels_offset = (pixels_per_interval * (int) (now % _getDelayPerInterval()))
            / (int) _getDelayPerInterval();
    final int last_interval_pos = dimension.width - axis_margin_right - pixels_offset;

    backing_g.setClip(axis_margin_left, 0, dimension.width - axis_margin_left - axis_margin_right,
            dimension.height);
    int current_interval_pos = last_interval_pos + pixels_per_interval;
    long current_time_to_display = time_to_display + _getDelayPerInterval();
    boolean stop = false;
    while (stop == false) {
        backing_g.setColor(Color.YELLOW.darker());
        backing_g.drawLine(current_interval_pos, axis_margin_top, current_interval_pos,
                dimension.height - axis_margin_bottom + std_separator);

        int cpt = 10;
        backing_g.setColor(Color.YELLOW.darker().darker().darker());
        while (--cpt > 0)
            if (current_interval_pos - cpt * (pixels_per_interval / 10) > axis_margin_left)
                backing_g.drawLine(current_interval_pos - cpt * (pixels_per_interval / 10), axis_margin_top + 1,
                        current_interval_pos - cpt * (pixels_per_interval / 10),
                        dimension.height - axis_margin_bottom - 1);

        final String current_time_str = formatTime(current_time_to_display);
        final String current_date_str = formatDate(current_time_to_display);
        final TextLayout current_layout = new TextLayout(current_time_str, backing_g.getFont(),
                backing_g.getFontRenderContext());
        final TextLayout current_layout_date = new TextLayout(current_date_str, backing_g.getFont(),
                backing_g.getFontRenderContext());
        final Rectangle2D current_bounds = current_layout.getBounds();
        final Rectangle2D current_bounds_date = current_layout_date.getBounds();
        backing_g.setColor(Color.YELLOW.darker());
        backing_g.drawString(current_time_str, current_interval_pos - (int) (current_bounds.getWidth() / 2),
                dimension.height - axis_margin_bottom + (int) current_bounds.getHeight() + 2 * std_separator);
        backing_g.setColor(Color.YELLOW.darker().darker());
        backing_g.drawString(current_date_str,
                current_interval_pos - (int) (current_bounds_date.getWidth() / 2),
                3 + ((int) current_bounds.getHeight()) + dimension.height - axis_margin_bottom
                        + (int) current_bounds.getHeight() + 2 * std_separator);
        if (current_interval_pos - current_bounds.getWidth() / 2 < axis_margin_left)
            stop = true;
        current_interval_pos -= pixels_per_interval;
        current_time_to_display -= _getDelayPerInterval();
    }
    backing_g.setClip(null);

    vinterval_pos = dimension.height - axis_margin_bottom - pixels_per_vinterval;
    int value = value_per_vinterval;
    while (vinterval_pos > axis_margin_top) {
        backing_g.setColor(Color.YELLOW.darker());
        backing_g.drawLine(axis_margin_left - std_separator, vinterval_pos, dimension.width - axis_margin_right,
                vinterval_pos);
        final String value_str;
        if (value >= 1000000)
            value_str = "" + value / 1000000 + "M";
        else if (value >= 1000)
            value_str = "" + value / 1000 + "k";
        else
            value_str = "" + value;
        final TextLayout current_layout = new TextLayout(value_str, backing_g.getFont(),
                backing_g.getFontRenderContext());
        final Rectangle2D current_bounds = current_layout.getBounds();
        backing_g.setColor(Color.YELLOW.darker());
        backing_g.drawString(value_str, axis_margin_left - (int) current_bounds.getWidth() - 2 * std_separator,
                vinterval_pos + (int) (current_bounds.getHeight() / 2));
        vinterval_pos -= pixels_per_vinterval;
        value += value_per_vinterval;
    }

    return now;
}

From source file:lcmc.common.ui.ResourceGraph.java

/** Returns layout of the text that will be drawn on the vertex. */
private TextLayout getVertexTextLayout(final Graphics2D g2d, final String text, final double fontSizeFactor) {
    final TextLayout ctl = textLayoutCache.get(fontSizeFactor + ":" + text);
    if (ctl != null) {
        return ctl;
    }/*w w  w . j av a  2s  .c om*/
    final Font font = mainData.getMainFrame().getFont();
    final FontRenderContext context = g2d.getFontRenderContext();
    final TextLayout tl = new TextLayout(text,
            new Font(font.getName(), font.getStyle(), (int) (font.getSize() * fontSizeFactor)), context);
    textLayoutCache.put(fontSizeFactor + ":" + text, tl);
    return tl;
}

From source file:lcmc.gui.ResourceGraph.java

/** Returns layout of the text that will be drawn on the vertex. */
private TextLayout getVertexTextLayout(final Graphics2D g2d, final String text, final double fontSizeFactor) {
    final TextLayout ctl = textLayoutCache.get(fontSizeFactor + ':' + text);
    if (ctl != null) {
        return ctl;
    }//from  w w  w  .ja  v a  2s . c  o m
    final Font font = Tools.getGUIData().getMainFrame().getFont();
    final FontRenderContext context = g2d.getFontRenderContext();
    TextLayout tl = new TextLayout(text,
            new Font(font.getName(), font.getStyle(), (int) (font.getSize() * fontSizeFactor)), context);
    textLayoutCache.put(fontSizeFactor + ':' + text, tl);
    return tl;
}

From source file:org.forester.archaeopteryx.TreePanel.java

final private void paintNodeData(final Graphics2D g, final PhylogenyNode node, final boolean to_graphics_file,
        final boolean to_pdf, final boolean is_in_found_nodes) {
    if (isNodeDataInvisible(node) && !to_graphics_file && !to_pdf) {
        return;//  w  w  w  . java  2s .  co  m
    }
    if (getOptions().isShowBranchLengthValues()
            && ((getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR)
                    || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED)
                    || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE))
            && (!node.isRoot()) && (node.getDistanceToParent() != PhylogenyNode.DISTANCE_DEFAULT)) {
        paintBranchLength(g, node, to_pdf, to_graphics_file);
    }
    if (!getControlPanel().isShowInternalData() && !node.isExternal() && !node.isCollapse()) {
        return;
    }
    int x = 0;
    if (node.getNodeData().isHasTaxonomy()
            && (getControlPanel().isShowTaxonomyCode() || getControlPanel().isShowTaxonomyNames())) {
        x = paintTaxonomy(g, node, is_in_found_nodes, to_pdf, to_graphics_file);
    }
    if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
        g.setColor(Color.BLACK);
    } else if (is_in_found_nodes) {
        g.setColor(getTreeColorSet().getFoundColor());
    } else if (getControlPanel().isColorAccordingToTaxonomy()) {
        g.setColor(getTaxonomyBasedColor(node));
    } else {
        g.setColor(getTreeColorSet().getSequenceColor());
    }
    _sb.setLength(0);
    if (node.isCollapse() && ((!node.isRoot() && !node.getParent().isCollapse()) || node.isRoot())) {
        _sb.append(" [");
        _sb.append(node.getAllExternalDescendants().size());
        _sb.append("]");
    }
    if (getControlPanel().isShowNodeNames() && (node.getNodeName().length() > 0)) {
        if (_sb.length() > 0) {
            _sb.append(" ");
        }
        _sb.append(node.getNodeName());
    }
    if (node.getNodeData().isHasSequence()) {
        if (getControlPanel().isShowGeneSymbols()
                && (node.getNodeData().getSequence().getSymbol().length() > 0)) {
            if (_sb.length() > 0) {
                _sb.append(" ");
            }
            _sb.append(node.getNodeData().getSequence().getSymbol());
        }
        if (getControlPanel().isShowGeneNames() && (node.getNodeData().getSequence().getName().length() > 0)) {
            //                if ( _sb.length() > 0 ) {
            //                    _sb.append( " " );
            //                }
            //                _sb.append( node.getNodeData().getSequence().getName() );
            PhylogenyNode parent = node.getParent();
            double x1 = parent.getXcoord();
            double y1 = parent.getYcoord();
            double x2 = node.getXcoord();
            double y2 = node.getYcoord();
            double above_the_line = 1.0;

            if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.TRIANGULAR) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = Math.abs(y1 + y2) / 2.0;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            } else if (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE) {
                double center_of_branch_x = Math.abs(x1 + x2) / 2.0 + EURO_D;
                double center_of_branch_y = y2;
                TreePanel.drawString(node.getNodeData().getSequence().getName(), center_of_branch_x,
                        center_of_branch_y - above_the_line, g);
            }

        }
        if (getControlPanel().isShowSequenceAcc()
                && (node.getNodeData().getSequence().getAccession() != null)) {
            if (_sb.length() > 0) {
                _sb.append(" ");
            }
            if (!ForesterUtil.isEmpty(node.getNodeData().getSequence().getAccession().getSource())) {
                _sb.append(node.getNodeData().getSequence().getAccession().getSource());
                _sb.append(":");
            }
            _sb.append(node.getNodeData().getSequence().getAccession().getValue());
        }
    }
    g.setFont(getTreeFontSet().getLargeFont());
    if (is_in_found_nodes) {
        g.setFont(getTreeFontSet().getLargeFont().deriveFont(Font.BOLD));
    }
    double down_shift_factor = 3.0;
    if (!node.isExternal() && (node.getNumberOfDescendants() == 1)) {
        down_shift_factor = 1;
    }
    // GUILHEM_BEG ______________
    final double posX = node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE;
    final double posY = (node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor));
    final int CONFIDENCE_LEFT_MARGIN = 4;
    final String sNodeText = _sb.toString();
    if (_control_panel.isShowSequenceRelations() && node.getNodeData().isHasSequence()
            && (_query_sequence != null)) {
        int nodeTextBoundsWidth = 0;
        if (sNodeText.length() > 0) {
            final Rectangle2D node_text_bounds = new TextLayout(sNodeText, g.getFont(), _frc).getBounds(); //would like to remove this 'new', but how...
            nodeTextBoundsWidth = (int) node_text_bounds.getWidth();
        }
        if (node.getNodeData().getSequence().equals(_query_sequence)) {
            if (nodeTextBoundsWidth > 0) { // invert font color and background color to show that this is the query sequence
                g.fillRect((int) posX - 1, (int) posY - 8, nodeTextBoundsWidth + 5, 11);
                g.setColor(getTreeColorSet().getBackgroundColor());
            }
        } else {
            final List<SequenceRelation> seqRelations = node.getNodeData().getSequence().getSequenceRelations();
            for (final SequenceRelation seqRelation : seqRelations) {
                final boolean fGotRelationWithQuery = (seqRelation.getRef0().isEqual(_query_sequence)
                        || seqRelation.getRef1().isEqual(_query_sequence))
                        && seqRelation.getType()
                                .equals(getControlPanel().getSequenceRelationTypeBox().getSelectedItem());
                if (fGotRelationWithQuery) { // we will underline the text to show that this sequence is ortholog to the query
                    final double linePosX = node.getXcoord() + 2 + TreePanel.HALF_BOX_SIZE;
                    final String sConfidence = (!getControlPanel().isShowSequenceRelationConfidence()
                            || (seqRelation.getConfidence() == null)) ? null
                                    : " (" + seqRelation.getConfidence().getValue() + ")";
                    if (sConfidence != null) {
                        double confidenceX = posX;
                        if (sNodeText.length() > 0) {
                            confidenceX += new TextLayout(sNodeText, g.getFont(), _frc).getBounds().getWidth()
                                    + CONFIDENCE_LEFT_MARGIN;
                        }
                        if (confidenceX > linePosX) { // let's only display confidence value if we are already displaying at least one of Prot/Gene Name and Taxonomy Code 
                            final int confidenceWidth = (int) new TextLayout(sConfidence, g.getFont(), _frc)
                                    .getBounds().getWidth();
                            TreePanel.drawString(sConfidence, confidenceX, posY, g);
                            x += CONFIDENCE_LEFT_MARGIN + confidenceWidth;
                        }
                    }
                    if (x + nodeTextBoundsWidth > 0) /* we only underline if there is something displayed */
                    {
                        if (nodeTextBoundsWidth == 0) {
                            nodeTextBoundsWidth -= 3; /* the gap between taxonomy code and node name should not be underlined if nothing comes after it */
                        } else {
                            nodeTextBoundsWidth += 2;
                        }
                        g.drawLine((int) linePosX + 1, 3 + (int) posY, (int) linePosX + x + nodeTextBoundsWidth,
                                3 + (int) posY);
                        break;
                    }
                }
            }
        }
    }
    if (sNodeText.length() > 0) {
        TreePanel.drawString(sNodeText, posX, posY, g);
    }
    // GUILHEM_END _____________
    // COMMENTED_OUT_BY_GUILHEM_BEG _______________
    // TODO FIXME need to check this one!
    //if ( _sb.length() > 0 ) {
    //    TreePanel.drawString( _sb.toString(), node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE, node.getYcoord()
    //            + ( getTreeFontSet()._fm_large.getAscent() / down_shift_factor ), g );
    //}
    // COMMENTED_OUT_BY_GUILHEM_END ________________
    if (getControlPanel().isShowAnnotation() && node.getNodeData().isHasSequence()
            && (node.getNodeData().getSequence().getAnnotations() != null)
            && (!node.getNodeData().getSequence().getAnnotations().isEmpty())) {
        if (_sb.length() > 0) {
            x += getTreeFontSet()._fm_large.stringWidth(_sb.toString()) + 5;
        }
        final Annotation ann = (Annotation) node.getNodeData().getSequence().getAnnotations().get(0);
        if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
            g.setColor(Color.BLACK);
        } else {
            g.setColor(calculateColorForAnnotation(ann));
        }
        final String ann_str = ann.asSimpleText().toString();
        TreePanel.drawString(ann_str, node.getXcoord() + x + 3 + TreePanel.HALF_BOX_SIZE,
                node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
        _sb.setLength(0);
        _sb.append(ann_str);
    }
    if ((getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.RECTANGULAR)
            || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.EURO_STYLE)
            || (getPhylogenyGraphicsType() == PHYLOGENY_GRAPHICS_TYPE.ROUNDED)) {
        if ((getControlPanel().isShowBinaryCharacters() || getControlPanel().isShowBinaryCharacterCounts())
                && node.getNodeData().isHasBinaryCharacters()) {
            if (_sb.length() > 0) {
                x += getTreeFontSet()._fm_large.stringWidth(_sb.toString()) + 5;
            }
            if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
                g.setColor(Color.BLACK);
            } else {
                g.setColor(getTreeColorSet().getBinaryDomainCombinationsColor());
            }
            if (getControlPanel().isShowBinaryCharacters()) {
                TreePanel.drawString(
                        node.getNodeData().getBinaryCharacters().getPresentCharactersAsStringBuffer()
                                .toString(),
                        node.getXcoord() + x + 1 + TreePanel.HALF_BOX_SIZE,
                        node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                paintGainedAndLostCharacters(g, node,
                        node.getNodeData().getBinaryCharacters().getGainedCharactersAsStringBuffer().toString(),
                        node.getNodeData().getBinaryCharacters().getLostCharactersAsStringBuffer().toString());
            } else {
                if (DRAW_MEAN_COUNTS && node.isInternal()) {
                    final List<PhylogenyNode> ec = node.getAllExternalDescendants();
                    double sum = 0;
                    int count = 0;
                    for (final PhylogenyNode phylogenyNode : ec) {
                        count++;
                        if (phylogenyNode.getNodeData().getBinaryCharacters() != null) {
                            sum += phylogenyNode.getNodeData().getBinaryCharacters().getPresentCount();
                        }
                    }
                    final double mean = ForesterUtil.round(sum / count, 1);
                    TreePanel.drawString(
                            node.getNodeData().getBinaryCharacters().getPresentCount() + " [" + mean + "]",
                            node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE,
                            node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                } else {
                    TreePanel.drawString(node.getNodeData().getBinaryCharacters().getPresentCount(),
                            node.getXcoord() + x + 2 + TreePanel.HALF_BOX_SIZE,
                            node.getYcoord() + (getTreeFontSet()._fm_large.getAscent() / down_shift_factor), g);
                }
                paintGainedAndLostCharacters(g, node,
                        "+" + node.getNodeData().getBinaryCharacters().getGainedCount(),
                        "-" + node.getNodeData().getBinaryCharacters().getLostCount());
            }
        }
    }
}

From source file:org.forester.archaeopteryx.TreePanel.java

final private int paintTaxonomy(final Graphics2D g, final PhylogenyNode node, final boolean is_in_found_nodes,
        final boolean to_pdf, final boolean to_graphics_file) {
    final Taxonomy taxonomy = node.getNodeData().getTaxonomy();
    g.setFont(getTreeFontSet().getLargeItalicFont());
    if ((to_pdf || to_graphics_file) && getOptions().isPrintBlackAndWhite()) {
        g.setColor(Color.BLACK);// w w  w  .ja  v a  2 s . c o  m
    } else if (is_in_found_nodes) {
        g.setFont(getTreeFontSet().getLargeItalicFont().deriveFont(TreeFontSet.BOLD_AND_ITALIC));
        g.setColor(getTreeColorSet().getFoundColor());
    } else if (getControlPanel().isColorAccordingToTaxonomy()) {
        g.setColor(getTaxonomyBasedColor(node));
    } else {
        g.setColor(getTreeColorSet().getTaxonomyColor());
    }
    final double start_x = node.getXcoord() + 3 + TreePanel.HALF_BOX_SIZE;
    final double start_y = node.getYcoord()
            + (getTreeFontSet()._fm_large.getAscent() / (node.getNumberOfDescendants() == 1 ? 1 : 3.0));
    _sb.setLength(0);
    if (_control_panel.isShowTaxonomyCode() && !ForesterUtil.isEmpty(taxonomy.getTaxonomyCode())) {
        _sb.append(taxonomy.getTaxonomyCode());
        _sb.append(" ");
    }
    if (_control_panel.isShowTaxonomyNames()) {
        if (!ForesterUtil.isEmpty(taxonomy.getScientificName())
                && !ForesterUtil.isEmpty(taxonomy.getCommonName())) {
            _sb.append(taxonomy.getScientificName());
            _sb.append(" (");
            _sb.append(taxonomy.getCommonName());
            _sb.append(") ");
        } else if (!ForesterUtil.isEmpty(taxonomy.getScientificName())) {
            _sb.append(taxonomy.getScientificName());
            _sb.append(" ");
        } else if (!ForesterUtil.isEmpty(taxonomy.getCommonName())) {
            _sb.append(taxonomy.getCommonName());
            _sb.append(" ");
        }
    }
    final String label = _sb.toString();
    /* GUILHEM_BEG */
    if ((label.length() > 0) && (node.getNodeData().isHasSequence())
            && node.getNodeData().getSequence().equals(_query_sequence)) {
        // invert font color and background color to show that this is the query sequence
        final Rectangle2D nodeTextBounds = new TextLayout(label, g.getFont(),
                new FontRenderContext(null, false, false)).getBounds();
        g.fillRect((int) start_x - 1, (int) start_y - 8, (int) nodeTextBounds.getWidth() + 4, 11);
        g.setColor(getTreeColorSet().getBackgroundColor());
    }
    /* GUILHEM_END */
    TreePanel.drawString(label, start_x, start_y, g);
    if (is_in_found_nodes) {
        return getTreeFontSet()._fm_large_italic_bold.stringWidth(label);
    } else {
        return getTreeFontSet()._fm_large_italic.stringWidth(label);
    }
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

public void init() {
    boolean emptyBackground = true;
    if (config.isUseImageBackground() && background != null) {
        ByteArrayInputStream is = new ByteArrayInputStream(background);
        JPEGImgDecoder decoder = new DefaultJPEGImgDecoder();
        try {/*from   w  w  w .  j a v a2 s.  c o  m*/
            this.image = decoder.decodeAsBufferedImage(is);
            this.width = image.getWidth();
            this.height = image.getHeight();
            emptyBackground = false;
        } catch (Exception e) {
            emptyBackground = true;
        }
    }
    if (emptyBackground) {
        this.width = config.getTextMarginLeft() * 2;
        this.height = config.getTextMarginBottom() * 6;
    }
    char[] chars = challengeId.toCharArray();
    charAttsList = new ArrayList();
    TextLayout text = null;
    AffineTransform textAt = null;
    String[] fontNames = config.getFontNames();
    for (int i = 0; i < chars.length; i++) {
        // font name
        String fontName = (fontNames.length == 1) ? fontNames[0] : fontNames[randomInt(0, fontNames.length)];

        // rise
        int rise = config.getTextRiseRange();
        if (rise > 0) {
            rise = randomInt(config.getTextMarginBottom(),
                    config.getTextMarginBottom() + config.getTextRiseRange());
        }

        if (config.getTextShear() > 0.0 || config.getTextRotation() > 0) {
            // rotation
            double dRotation = 0.0;
            if (config.getTextRotation() > 0) {
                dRotation = Math.toRadians(randomInt(-(config.getTextRotation()), config.getTextRotation()));
            }

            // shear
            double shearX = 0.0;
            double shearY = 0.0;
            if (config.getTextShear() > 0.0) {
                Random ran = new Random();
                shearX = ran.nextDouble() * config.getTextShear();
                shearY = ran.nextDouble() * config.getTextShear();
            }
            CharAttributes cf = new CharAttributes(chars[i], fontName, dRotation, rise, shearX, shearY);
            charAttsList.add(cf);
            text = new TextLayout(chars[i] + "", getFont(fontName),
                    new FontRenderContext(null, config.isFontAntialiasing(), false));
            textAt = new AffineTransform();
            if (config.getTextRotation() > 0)
                textAt.rotate(dRotation);
            if (config.getTextShear() > 0.0)
                textAt.shear(shearX, shearY);
        } else {
            CharAttributes cf = new CharAttributes(chars[i], fontName, 0, rise, 0.0, 0.0);
            charAttsList.add(cf);
        }
        if (emptyBackground) {
            Shape shape = text.getOutline(textAt);
            //                this.width += text.getBounds().getWidth();
            this.width += (int) shape.getBounds2D().getWidth();
            this.width += config.getTextSpacing() + 1;
            if (this.height < (int) shape.getBounds2D().getHeight() + rise) {
                this.height = (int) shape.getBounds2D().getHeight() + rise;
            }
        }
    }
    if (emptyBackground) {
        this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gfx = (Graphics2D) this.image.getGraphics();
        gfx.setBackground(Color.WHITE);
        gfx.clearRect(0, 0, width, height);
    }
}

From source file:org.apache.jetspeed.security.mfa.impl.CaptchaImageResource.java

/**
 * Renders this image//from   w  w  w .ja v  a 2  s  .c  o  m
 * 
 * @return The image data
 */
private final byte[] render() throws IOException {
    Graphics2D gfx = (Graphics2D) this.image.getGraphics();
    if (config.isFontAntialiasing())
        gfx.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    int curWidth = config.getTextMarginLeft();
    FontRenderContext ctx = new FontRenderContext(null, config.isFontAntialiasing(), false);
    for (int i = 0; i < charAttsList.size(); i++) {
        CharAttributes cf = (CharAttributes) charAttsList.get(i);
        TextLayout text = new TextLayout(cf.getChar() + "", getFont(cf.getName()), ctx); //gfx.getFontRenderContext());
        AffineTransform textAt = new AffineTransform();
        textAt.translate(curWidth, this.height - cf.getRise());
        if (cf.getRotation() != 0) {
            textAt.rotate(cf.getRotation());
        }
        if (cf.getShearX() > 0.0)
            textAt.shear(cf.getShearX(), cf.getShearY());
        Shape shape = text.getOutline(textAt);
        curWidth += shape.getBounds().getWidth() + config.getTextSpacing();
        if (config.isUseImageBackground())
            gfx.setColor(Color.BLACK);
        else
            gfx.setXORMode(Color.BLACK);
        gfx.fill(shape);
    }
    if (config.isEffectsNoise()) {
        noiseEffects(gfx, image);
    }
    if (config.isUseTimestamp()) {
        if (config.isEffectsNoise())
            gfx.setColor(Color.WHITE);
        else
            gfx.setColor(Color.BLACK);

        TimeZone tz = TimeZone.getTimeZone(config.getTimestampTZ());
        Calendar cal = new GregorianCalendar(tz);
        SimpleDateFormat formatter;
        if (config.isUseTimestamp24hr())
            formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss z");
        else
            formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a, z");
        formatter.setTimeZone(tz);
        Font font = gfx.getFont();
        Font newFont = new Font(font.getName(), font.getStyle(), config.getTimestampFontSize());
        gfx.setFont(newFont);
        gfx.drawString(formatter.format(cal.getTime()), config.getTextMarginLeft() * 4, this.height - 1);
    }

    return toImageData(image);
}

From source file:org.dishevelled.brainstorm.BrainStorm.java

/**
 * Calculate the text area size in rows and columns based on the current
 * window size and text area font size./*from  www  .  j  a  va2  s .  c om*/
 */
private void calculateTextAreaSize() {
    double width = (double) getWidth();
    FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
    TextLayout textLayout = new TextLayout("W", textArea.getFont(), frc);
    Rectangle2D textBounds = textLayout.getBounds();
    int columns = Math.min(45, (int) (width / textBounds.getWidth()) - 4);
    textArea.setColumns(columns);
}

From source file:org.earthtime.UPb_Redux.dateInterpretation.WeightedMeanGraphPanel.java

private void drawAxesAndTicks(Graphics2D g2d, double rangeX, double rangeY) {

    // oct 2014 new tic logic
    // reset the clip bounds to paint axis and numbers
    g2d.setClip(0, 0, getWidth(), getHeight());

    g2d.setFont(new Font("Monospaced", Font.BOLD, 14));
    g2d.setPaint(Color.BLACK);/*from  w w w  . j  a v  a 2 s .  co  m*/
    g2d.setStroke(new BasicStroke(2.0f));

    // determine the axis ticks
    BigDecimal[] tics = TicGeneratorForAxes.generateTics(getMinY_Display(), getMaxY_Display(), 12);
    // trap for bad plot
    if (tics.length <= 1) {
        tics = new BigDecimal[0];
    }
    double minXDisplay = 0.0;
    int yAxisTicWidth = 8;
    int yTicLabelFrequency = 2;
    int labeledTicCountYAxis = 0;

    g2d.setPaint(Color.black);
    for (int i = 0; i < tics.length; i++) {

        double y = tics[i].doubleValue();

        if ((y > getMinY_Display()) // dont print across mappedX axis
                && (y < getMaxY_Display())) // dont print across top border
        {
            try {
                Shape ticMark = new Line2D.Double( //
                        mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth),
                        mapY(y, getMaxY_Display(), rangeY, graphHeight),
                        mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) + 7,
                        mapY(y, getMaxY_Display(), rangeY, graphHeight));
                g2d.draw(ticMark);

                String intString = "00000" + tics[i].toPlainString().replace(".", "");
                int lastPlace = Integer.parseInt(intString.substring(intString.length() - 4));

                if (lastPlace % yTicLabelFrequency == 0) {
                    if (labeledTicCountYAxis % yTicLabelFrequency == 0) {

                        TextLayout mLayout = //
                                new TextLayout(tics[i].toPlainString(), g2d.getFont(),
                                        g2d.getFontRenderContext());

                        Rectangle2D bounds = mLayout.getBounds();

                        //if (isyAxisHorizontalTicLabels()) {
                        //                            g2d.drawString(tics[i].toPlainString(),//
                        //                                    (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
                        //                                    (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + 30f);
                        //                            } else {
                        float yLabelCenterOffset = (float) mLayout.getBounds().getWidth() / 2f;

                        g2d.rotate(-Math.PI / 2.0,
                                (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
                                (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + yLabelCenterOffset);
                        g2d.drawString(tics[i].toPlainString(),
                                (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
                                (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + yLabelCenterOffset);
                        g2d.rotate(Math.PI / 2.0,
                                (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
                                (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + yLabelCenterOffset);
                    }

                    labeledTicCountYAxis++;
                } else {

                    if (labeledTicCountYAxis > 0) {
                        labeledTicCountYAxis++;
                    }
                }
            } catch (Exception e) {
            }
        }
    }

    ////        // reset the clip bounds to paint axis and numbers
    ////        g2d.setClip(0, 0, getWidth(), getHeight());
    ////
    ////        g2d.setFont(new Font("Monospaced", Font.BOLD, 14));
    ////        g2d.setPaint(Color.BLACK);
    ////        g2d.setStroke(new BasicStroke(2.0f));
    ////
    ////        // determine the axis ticks
    ////        double minYtick = Math.ceil(getMinY_Display() * 100) / 100;
    ////        double maxYtick = Math.floor(getMaxY_Display() * 100) / 100;
    ////
    ////        int count = 0;
    ////        double deltay = Math.rint((maxYtick - minYtick) * 10 + 0.5);
    ////        double stepYtick = deltay / 100;
    ////
    ////        for (double y = minYtick; y
    ////                < maxYtick; y
    ////                += stepYtick) {
    ////            Line2D line = new Line2D.Double(
    ////                    mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth),
    ////                    mapY(y, getMaxY_Display(), rangeY, graphHeight),
    ////                    mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) + 7,
    ////                    mapY(y, getMaxY_Display(), rangeY, graphHeight));
    ////            g2d.draw(line);
    ////
    ////            if ((count % 2) == 1) {
    ////                NumberFormat yFormat = null;
    ////                String temp = null;
    ////
    ////                yFormat
    ////                        = new DecimalFormat("0.00");
    ////                temp
    ////                        = yFormat.format(y);
    ////
    ////                g2d.setPaint(Color.black);
    ////                g2d.rotate(
    ////                        -Math.PI / 2.0,
    ////                        (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
    ////                        (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + 30f);
    ////                g2d.drawString(
    ////                        temp,
    ////                        (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
    ////                        (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + 30f);
    ////                g2d.rotate(
    ////                        Math.PI / 2.0,
    ////                        (float) mapX(getMinX_Display(), getMinX_Display(), rangeX, graphWidth) - 4f,
    ////                        (float) mapY(y, getMaxY_Display(), rangeY, graphHeight) + 30f);
    ////
    ////            }
    ////
    ////            count++;
    ////
    ////        }
    // draw and label axes
    g2d.setFont(new Font("Monospaced", Font.BOLD, 20));
    g2d.drawRect(getLeftMargin(), getTopMargin(), getGraphWidth() - 1, getGraphHeight() - 1);

}

From source file:org.photovault.swingui.PhotoCollectionThumbView.java

private void paintThumbnail(Graphics2D g2, PhotoInfo photo, int startx, int starty, boolean isSelected) {
    log.debug("paintThumbnail entry " + photo.getUuid());
    long startTime = System.currentTimeMillis();
    long thumbReadyTime = 0;
    long thumbDrawnTime = 0;
    long endTime = 0;
    // Current position in which attributes can be drawn
    int ypos = starty + rowHeight / 2;
    boolean useOldThumbnail = false;

    Thumbnail thumbnail = null;/* w  w  w  .  j a v a 2 s  . com*/
    log.debug("finding thumb");
    boolean hasThumbnail = photo.hasThumbnail();
    log.debug("asked if has thumb");
    if (hasThumbnail) {
        log.debug("Photo " + photo.getUuid() + " has thumbnail");
        thumbnail = photo.getThumbnail();
        log.debug("got thumbnail");
    } else {
        /*
         Check if the thumbnail has been just invalidated. If so, use the 
         old one until we get the new thumbnail created.
         */
        thumbnail = photo.getOldThumbnail();
        if (thumbnail != null) {
            useOldThumbnail = true;
        } else {
            // No success, use default thumnail.
            thumbnail = Thumbnail.getDefaultThumbnail();
        }

        // Inform background task scheduler that we have some work to do
        ctrl.getBackgroundTaskScheduler().registerTaskProducer(this, TaskPriority.CREATE_VISIBLE_THUMBNAIL);
    }
    thumbReadyTime = System.currentTimeMillis();

    log.debug("starting to draw");
    // Find the position for the thumbnail
    BufferedImage img = thumbnail.getImage();
    if (img == null) {
        thumbnail = Thumbnail.getDefaultThumbnail();
        img = thumbnail.getImage();
    }

    float scaleX = ((float) thumbWidth) / ((float) img.getWidth());
    float scaleY = ((float) thumbHeight) / ((float) img.getHeight());
    float scale = Math.min(scaleX, scaleY);
    int w = (int) (img.getWidth() * scale);
    int h = (int) (img.getHeight() * scale);

    int x = startx + (columnWidth - w) / (int) 2;
    int y = starty + (rowHeight - h) / (int) 2;

    log.debug("drawing thumbnail");

    // Draw shadow
    int offset = isSelected ? 2 : 0;
    int shadowX[] = { x + 3 - offset, x + w + 1 + offset, x + w + 1 + offset };
    int shadowY[] = { y + h + 1 + offset, y + h + 1 + offset, y + 3 - offset };
    GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD, shadowX.length);
    polyline.moveTo(shadowX[0], shadowY[0]);
    for (int index = 1; index < shadowX.length; index++) {
        polyline.lineTo(shadowX[index], shadowY[index]);
    }
    ;
    BasicStroke shadowStroke = new BasicStroke(4.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
    Stroke oldStroke = g2.getStroke();
    g2.setStroke(shadowStroke);
    g2.setColor(Color.DARK_GRAY);
    g2.draw(polyline);
    g2.setStroke(oldStroke);

    // Paint thumbnail
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g2.drawImage(img, new AffineTransform(scale, 0f, 0f, scale, x, y), null);
    if (useOldThumbnail) {
        creatingThumbIcon.paintIcon(this, g2,
                startx + (columnWidth - creatingThumbIcon.getIconWidth()) / (int) 2,
                starty + (rowHeight - creatingThumbIcon.getIconHeight()) / (int) 2);
    }
    log.debug("Drawn, drawing decorations");
    if (isSelected) {
        Stroke prevStroke = g2.getStroke();
        Color prevColor = g2.getColor();
        g2.setStroke(new BasicStroke(3.0f));
        g2.setColor(Color.BLUE);
        g2.drawRect(x, y, w, h);
        g2.setColor(prevColor);
        g2.setStroke(prevStroke);
    }

    thumbDrawnTime = System.currentTimeMillis();

    boolean drawAttrs = (thumbWidth >= 100);
    if (drawAttrs) {
        // Increase ypos so that attributes are drawn under the image
        ypos += ((int) h) / 2 + 3;

        // Draw the attributes

        // Draw the qualoity icon to the upper left corner of the thumbnail
        int quality = photo.getQuality();
        if (showQuality && quality != 0) {
            int qx = startx + (columnWidth - quality * starIcon.getIconWidth()) / (int) 2;
            for (int n = 0; n < quality; n++) {
                starIcon.paintIcon(this, g2, qx, ypos);
                qx += starIcon.getIconWidth();
            }
            ypos += starIcon.getIconHeight();
        }
        ypos += 6;

        if (photo.getRawSettings() != null) {
            // Draw the "RAW" icon
            int rx = startx + (columnWidth + w - rawIcon.getIconWidth()) / (int) 2 - 5;
            int ry = starty + (columnWidth - h - rawIcon.getIconHeight()) / (int) 2 + 5;
            rawIcon.paintIcon(this, g2, rx, ry);
        }
        if (photo.getHistory().getHeads().size() > 1) {
            // Draw the "unresolved conflicts" icon
            int rx = startx + (columnWidth + w - 10) / (int) 2 - 20;
            int ry = starty + (columnWidth - h - 10) / (int) 2;
            g2.setColor(Color.RED);
            g2.fillRect(rx, ry, 10, 10);
        }

        Color prevBkg = g2.getBackground();
        if (isSelected) {
            g2.setBackground(Color.BLUE);
        } else {
            g2.setBackground(this.getBackground());
        }
        Font attrFont = new Font("Arial", Font.PLAIN, 10);
        FontRenderContext frc = g2.getFontRenderContext();
        if (showDate && photo.getShootTime() != null) {
            FuzzyDate fd = new FuzzyDate(photo.getShootTime(), photo.getTimeAccuracy());

            String dateStr = fd.format();
            TextLayout txt = new TextLayout(dateStr, attrFont, frc);
            // Calculate the position for the text
            Rectangle2D bounds = txt.getBounds();
            int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX();
            g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4);
            txt.draw(g2, xpos, (int) (ypos + bounds.getHeight()));
            ypos += bounds.getHeight() + 4;
        }
        String shootPlace = photo.getShootingPlace();
        if (showPlace && shootPlace != null && shootPlace.length() > 0) {
            TextLayout txt = new TextLayout(photo.getShootingPlace(), attrFont, frc);
            // Calculate the position for the text
            Rectangle2D bounds = txt.getBounds();
            int xpos = startx + ((int) (columnWidth - bounds.getWidth())) / 2 - (int) bounds.getMinX();

            g2.clearRect(xpos - 2, ypos - 2, (int) bounds.getWidth() + 4, (int) bounds.getHeight() + 4);
            txt.draw(g2, xpos, (int) (ypos + bounds.getHeight()));
            ypos += bounds.getHeight() + 4;
        }
        g2.setBackground(prevBkg);
    }
    endTime = System.currentTimeMillis();
    log.debug("paintThumbnail: exit " + photo.getUuid());
    log.debug("Thumb fetch " + (thumbReadyTime - startTime) + " ms");
    log.debug("Thumb draw " + (thumbDrawnTime - thumbReadyTime) + " ms");
    log.debug("Deacoration draw " + (endTime - thumbDrawnTime) + " ms");
    log.debug("Total " + (endTime - startTime) + " ms");
}