Example usage for java.awt FontMetrics charWidth

List of usage examples for java.awt FontMetrics charWidth

Introduction

In this page you can find the example usage for java.awt FontMetrics charWidth.

Prototype

public int charWidth(char ch) 

Source Link

Document

Returns the advance width of the specified character in this Font .

Usage

From source file:org.ofbiz.common.CommonEvents.java

public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) {
    try {//from ww w  . j a  v a 2 s .c  om
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"),
                "default");
        final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha.properties",
                "captcha." + captchaSizeConfigName, delegator);
        final String[] captchaSizeConfigs = captchaSizeConfig.split("\\|");
        final String captchaCodeId = StringUtils.defaultIfEmpty(request.getParameter("captchaCodeId"), ""); // this is used to uniquely identify in the user session the attribute where the captcha code for the last captcha for the form is stored

        final int fontSize = Integer.parseInt(captchaSizeConfigs[0]);
        final int height = Integer.parseInt(captchaSizeConfigs[1]);
        final int width = Integer.parseInt(captchaSizeConfigs[2]);
        final int charsToPrint = UtilProperties.getPropertyAsInteger("captcha.properties",
                "captcha.code_length", 6);
        final char[] availableChars = EntityUtilProperties
                .getPropertyValue("captcha.properties", "captcha.characters", delegator).toCharArray();

        //It is possible to pass the font size, image width and height with the request as well
        Color backgroundColor = Color.gray;
        Color borderColor = Color.DARK_GRAY;
        Color textColor = Color.ORANGE;
        Color circleColor = new Color(160, 160, 160);
        Font textFont = new Font("Arial", Font.PLAIN, fontSize);
        int circlesToDraw = 6;
        float horizMargin = 20.0f;
        double rotationRange = 0.7; // in radians
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = (Graphics2D) bufferedImage.getGraphics();

        g.setColor(backgroundColor);
        g.fillRect(0, 0, width, height);

        //Generating some circles for background noise
        g.setColor(circleColor);
        for (int i = 0; i < circlesToDraw; i++) {
            int circleRadius = (int) (Math.random() * height / 2.0);
            int circleX = (int) (Math.random() * width - circleRadius);
            int circleY = (int) (Math.random() * height - circleRadius);
            g.drawOval(circleX, circleY, circleRadius * 2, circleRadius * 2);
        }
        g.setColor(textColor);
        g.setFont(textFont);

        FontMetrics fontMetrics = g.getFontMetrics();
        int maxAdvance = fontMetrics.getMaxAdvance();
        int fontHeight = fontMetrics.getHeight();

        String captchaCode = RandomStringUtils.random(6, availableChars);

        float spaceForLetters = -horizMargin * 2 + width;
        float spacePerChar = spaceForLetters / (charsToPrint - 1.0f);

        for (int i = 0; i < captchaCode.length(); i++) {

            // this is a separate canvas used for the character so that
            // we can rotate it independently
            int charWidth = fontMetrics.charWidth(captchaCode.charAt(i));
            int charDim = Math.max(maxAdvance, fontHeight);
            int halfCharDim = (charDim / 2);

            BufferedImage charImage = new BufferedImage(charDim, charDim, BufferedImage.TYPE_INT_ARGB);
            Graphics2D charGraphics = charImage.createGraphics();
            charGraphics.translate(halfCharDim, halfCharDim);
            double angle = (Math.random() - 0.5) * rotationRange;
            charGraphics.transform(AffineTransform.getRotateInstance(angle));
            charGraphics.translate(-halfCharDim, -halfCharDim);
            charGraphics.setColor(textColor);
            charGraphics.setFont(textFont);

            int charX = (int) (0.5 * charDim - 0.5 * charWidth);
            charGraphics.drawString("" + captchaCode.charAt(i), charX,
                    ((charDim - fontMetrics.getAscent()) / 2 + fontMetrics.getAscent()));

            float x = horizMargin + spacePerChar * (i) - charDim / 2.0f;
            int y = ((height - charDim) / 2);

            g.drawImage(charImage, (int) x, y, charDim, charDim, null, null);

            charGraphics.dispose();
        }
        // Drawing the image border
        g.setColor(borderColor);
        g.drawRect(0, 0, width - 1, height - 1);
        g.dispose();
        response.setContentType("image/jpeg");
        ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        HttpSession session = request.getSession();
        Map<String, String> captchaCodeMap = UtilGenerics.checkMap(session.getAttribute("_CAPTCHA_CODE_"));
        if (captchaCodeMap == null) {
            captchaCodeMap = new HashMap<String, String>();
            session.setAttribute("_CAPTCHA_CODE_", captchaCodeMap);
        }
        captchaCodeMap.put(captchaCodeId, captchaCode);
    } catch (Exception ioe) {
        Debug.logError(ioe.getMessage(), module);
    }
    return "success";
}

From source file:org.shredzone.commons.captcha.impl.DefaultCaptchaGenerator.java

/**
 * Draws a single character.//from   w ww.jav a  2 s . co  m
 *
 * @param g2d
 *            {@link Graphics2D} context
 * @param ch
 *            character to draw
 * @param x
 *            left x position of the character
 * @param boxWidth
 *            width of the box
 */
private void drawCharacter(Graphics2D g2d, char ch, int x, int boxWidth) {
    double degree = (rnd.nextDouble() * rotationAmplitude * 2) - rotationAmplitude;
    double scale = 1 - (rnd.nextDouble() * scaleAmplitude / 100);

    Graphics2D cg2d = (Graphics2D) g2d.create();
    cg2d.setFont(font.deriveFont(fontSize));

    cg2d.translate(x + (boxWidth / 2), height / 2);
    cg2d.rotate(degree * PI / 90);
    cg2d.scale(scale, scale);

    FontMetrics fm = cg2d.getFontMetrics();
    int charWidth = fm.charWidth(ch);
    int charHeight = fm.getAscent() + fm.getDescent();

    cg2d.drawString(String.valueOf(ch), -(charWidth / 2), fm.getAscent() - (charHeight / 2));

    cg2d.dispose();
}

From source file:StringRectPaintPanel.java

public void paint(Graphics g) {
    g.setFont(new Font("", 0, 100));
    FontMetrics fm = getFontMetrics(new Font("", 0, 100));
    String s = "java2s";
    int x = 5;//from   w ww  .j  av a  2s.  c om
    int y = 5;

    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);

        int h = fm.getHeight();
        int w = fm.charWidth(c);

        g.drawRect(x, y, w, h);
        g.drawString(String.valueOf(c), x, y + h);

        x = x + w;
    }
}

From source file:com.intel.stl.ui.common.view.ComponentFactory.java

/**
 * //from  www  . j a va  2  s.  c  o  m
 * <i>Description:</i> simple method that creates single/multi line label
 * with specified label width based on a source label. For more advanced
 * label attributes, it's the developer's responsibility to set them back.
 * 
 * @param source
 * @param wrap
 * @param maxWidth
 * @return
 */
public static JLabel deriveLabel(JLabel source, final boolean wrap, final int maxWidth) {
    JXLabel label = new JXLabel(source.getText(), source.getIcon(), source.getHorizontalAlignment()) {
        private static final long serialVersionUID = -4816144910055350011L;

        private Font cachedFont;

        private String chahedRawText, chahedText;

        /*
         * (non-Javadoc)
         * 
         * @see javax.swing.JLabel#getText()
         */
        @Override
        public String getText() {
            String text = super.getText();
            if (wrap || maxWidth <= 0 || text == null || text.isEmpty()) {
                return text;
            }

            if (getFont().equals(cachedFont) && text.equals(chahedRawText)) {
                return chahedText;
            }

            chahedRawText = text;
            cachedFont = getFont();
            FontMetrics fm = getFontMetrics(cachedFont);
            char[] chars = text.toCharArray();
            int width = fm.charsWidth(chars, 0, chars.length);
            if (width < maxWidth) {
                chahedText = text;
            } else {
                width += fm.charWidth('.') * 3;
                int pos = chars.length - 1;
                for (; pos >= 0 && width > maxWidth; pos--) {
                    width -= fm.charWidth(chars[pos]);
                }
                chahedText = new String(chars, 0, pos) + "...";
                if (getToolTipText() == null) {
                    setToolTipText(text);
                }
            }

            return chahedText;
        }

    };
    if (wrap) {
        label.setLineWrap(true);
    }
    if (maxWidth > 0) {
        label.setMaxLineSpan(maxWidth);
    }
    label.setEnabled(source.isEnabled());
    label.setForeground(source.getForeground());
    label.setOpaque(source.isOpaque());
    label.setBackground(source.getBackground());
    label.setFont(source.getFont());
    label.setBorder(source.getBorder());
    label.setToolTipText(source.getToolTipText());
    return label;
}

From source file:co.id.app.sys.util.StringUtils.java

public static String getMakeLiner(String temp, int widLimitMetric) {
    if (temp == null) {
        return null;
    }//from  w  w w  .  j  a  v a  2s  .c om
    String strLiner = "";
    Font ft = new Font("Arial, Helvetica, sans-serif", Font.TRUETYPE_FONT, 9);
    JComponent jx = new JComponent() {
        private static final long serialVersionUID = 2792190024722186161L;
    };
    jx.setFont(ft);
    FontMetrics fm = jx.getFontMetrics(ft);
    int strWidMetric = fm.stringWidth(temp);
    while (strWidMetric > 0) {
        char[] ch = temp.toCharArray();
        if (strWidMetric > widLimitMetric) {
            int wChTot = 0;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; wChTot < widLimitMetric; i++) {
                wChTot += fm.charWidth(ch[i]);
                sb.append(ch[i]);
            }

            String strWid = sb.toString();
            int lastChar13 = strWid.lastIndexOf(" ");
            if (lastChar13 != -1) {
                strWid = temp.substring(0, lastChar13);
                strLiner = strLiner + strWid + "<br/>";
                temp = temp.substring(lastChar13 + 1, temp.length());
                strWidMetric = fm.stringWidth(temp);
            } else {
                strWid = temp.substring(0, strWid.length());
                strLiner = strLiner + strWid + "<br/>";
                temp = temp.substring(strWid.length(), temp.length());
                strWidMetric = fm.stringWidth(temp);
            }
        } else {
            strLiner = strLiner + temp;
            temp = "";
            strWidMetric = fm.stringWidth(temp);
        }

    }
    return strLiner;
}

From source file:com.intuit.tank.tools.debugger.FindReplaceDialog.java

/**
 * Constructs a new find dialog according to the specified type of dialog requested. The dialog can be either a FIND
 * dialog, either a REPLACE dialog. In both cases, components displayed remain the sames, but the ones specific to
 * replace feature are grayed out.//from w  ww.  j a  v  a  2  s  .  co  m
 * 
 * @param parent
 *            The window holder
 * @param type
 *            The type of the dialog: FindReplace.FIND or FindReplace.REPLACE
 * @param modal
 *            Displays dialog as a modal window if true
 */

public FindReplaceDialog(AgentDebuggerFrame parent, DialogType type) {
    super(parent, type == DialogType.REPLACE ? "Replace" : "Find", true);
    this.parent = parent;

    cbSearch = new JComboBox();
    cbSearch.setEditable(true);
    cbReplace = new JComboBox();
    cbReplace.setEditable(true);
    KeyHandler handler = new KeyHandler();
    tfSearchEditor = (JTextField) cbSearch.getEditor().getEditorComponent();
    tfSearchEditor.addKeyListener(handler);
    tfReplaceEditor = (JTextField) cbReplace.getEditor().getEditorComponent();
    tfReplaceEditor.addKeyListener(handler);

    GridBagLayout gridbag = new GridBagLayout();
    GridBagConstraints constraints = new GridBagConstraints();
    getContentPane().setLayout(gridbag);
    ((JPanel) getContentPane()).setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
    int gridX = 0;
    int gridY = 0;
    JLabel findLabel = new JLabel("Find");
    buildConstraints(constraints, gridX, gridY, 1, 1, 0, 0);
    constraints.anchor = GridBagConstraints.WEST;
    gridbag.setConstraints(findLabel, constraints);
    getContentPane().add(findLabel);
    gridX++;

    buildConstraints(constraints, gridX, gridY, 1, 1, 100, 0);
    constraints.fill = GridBagConstraints.HORIZONTAL;
    constraints.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(cbSearch, constraints);
    getContentPane().add(cbSearch);
    gridX++;

    btnFind = new JButton("Find");
    btnFind.setToolTipText("Find text in scripts");
    btnFind.setMnemonic('F');
    btnFind.addActionListener(this);
    buildConstraints(constraints, gridX, gridY, 1, 1, 0, 0);
    constraints.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(btnFind, constraints);
    getContentPane().add(btnFind);
    getRootPane().setDefaultButton(btnFind);
    gridX++;

    btnCancel = new JButton("Cancel");
    btnCancel.setMnemonic('C');
    btnCancel.addActionListener(this);
    buildConstraints(constraints, gridX, gridY, 1, 1, 0, 0);
    constraints.anchor = GridBagConstraints.CENTER;
    gridbag.setConstraints(btnCancel, constraints);
    getContentPane().add(btnCancel);
    gridY++;
    gridX = 0;
    if (type == DialogType.REPLACE) {
        JLabel replaceLabel = new JLabel("Replace");
        buildConstraints(constraints, gridX, gridY, 1, 1, 0, 0);
        constraints.anchor = GridBagConstraints.WEST;
        gridbag.setConstraints(replaceLabel, constraints);
        getContentPane().add(replaceLabel);
        gridX++;

        buildConstraints(constraints, gridX, gridY, 1, 1, 100, 0);
        constraints.fill = GridBagConstraints.HORIZONTAL;
        constraints.anchor = GridBagConstraints.CENTER;
        gridbag.setConstraints(cbReplace, constraints);
        getContentPane().add(cbReplace);
        gridX++;

        btnReplace = new JButton("Replace");
        btnReplace.setToolTipText("REplace in script");
        btnReplace.setMnemonic('R');
        btnReplace.addActionListener(this);
        buildConstraints(constraints, gridX, gridY, 1, 1, 0, 0);
        constraints.anchor = GridBagConstraints.CENTER;
        gridbag.setConstraints(btnReplace, constraints);
        getContentPane().add(btnReplace);
        gridX++;

        btnReplaceAll = new JButton("Replace All");
        btnReplaceAll.addActionListener(this);
        buildConstraints(constraints, gridX, gridY, 1, 1, 0, 0);
        constraints.anchor = GridBagConstraints.CENTER;
        gridbag.setConstraints(btnReplaceAll, constraints);
        getContentPane().add(btnReplaceAll);
        btnReplace.addKeyListener(handler);
        btnReplaceAll.addKeyListener(handler);
        gridY++;
        gridX = 0;
    }

    TitledBorder border = new TitledBorder("Options");
    JPanel panel = new JPanel(new GridLayout(1, 4));
    panel.setBorder(border);
    checkboxWrap = new JCheckBox("Wrap Search");
    panel.add(checkboxWrap);

    checkboxMatchCase = new JCheckBox("Case sensitive");
    panel.add(checkboxMatchCase);

    checkboxRegexp = new JCheckBox("Regular expressions");
    panel.add(checkboxRegexp);

    buildConstraints(constraints, gridX, gridY, 4, 1, 100, 100);
    constraints.anchor = GridBagConstraints.WEST;
    gridbag.setConstraints(panel, constraints);
    getContentPane().add(panel);

    FontMetrics fm = getFontMetrics(getFont());
    cbSearch.setPreferredSize(new Dimension(18 * fm.charWidth('m'), (int) cbSearch.getPreferredSize().height));
    cbReplace
            .setPreferredSize(new Dimension(18 * fm.charWidth('m'), (int) cbReplace.getPreferredSize().height));

    pack();
    // setResizable(false);
    WindowUtil.centerOnParent(this);

    // patch by MJB 8/1/2002
    btnFind.addKeyListener(handler);

    btnCancel.addKeyListener(handler);
    checkboxMatchCase.addKeyListener(handler);
    checkboxRegexp.addKeyListener(handler);

}

From source file:org.openmicroscopy.shoola.util.ui.omeeditpane.OMEWikiComponent.java

/** 
 * Invokes when the text needs to be wrapped.
 * /*from  ww  w.j a v  a 2s  . c o  m*/
 * @param width The width to use.
 * @param newLineStr The string used for new line.
 */
public void wrapText(int width, String newLineStr) {
    if (!wrapWord || pane == null)
        return;
    String value = getText();
    if (value == null)
        return;
    value = prepare(value, false);
    FontMetrics fm = getFontMetrics(getFont());
    int charWidth = fm.charWidth('m');
    columns = (int) (1.5 * width) / charWidth;
    setText(WordUtils.wrap(value, columns, newLineStr, false));
}

From source file:org.colombbus.tangara.EditorFrame.java

/**
 * This method changes the standard size of a TAB for a given JTextPane.
 *
 * @param the//w  ww . j a  v a  2  s. com
 *            JTextPane where to apply this method.
 */
public void setTabSizeOf(JTextPane textPane) {
    int spacesPerTab = tabSize;
    FontMetrics fm = textPane.getFontMetrics(textPane.getFont());
    int charWidth = fm.charWidth(' ');
    int tabWidth = charWidth * spacesPerTab;

    TabStop[] tabStops = new TabStop[200];

    for (int j = 0; j < tabStops.length; j++) {
        int tab = j + 1;
        tabStops[j] = new TabStop(tab * tabWidth);
    }

    TabSet tabSet = new TabSet(tabStops);

    Style style = textPane.getLogicalStyle();
    StyleConstants.setTabSet(style, tabSet);
    textPane.setLogicalStyle(style);
}

From source file:ded.ui.DiagramController.java

/** Check to see if the font is rendering properly.  I have had a
  * lot of trouble getting this to work on a wide range of
  * machines and JVMs.  If the font rendering does not work, just
  * alert the user to the problem but keep going. */
public void checkFontRendering() {
    // Render the glyph for 'A' in a box just large enough to
    // contain it when rendered properly.
    int width = 9;
    int height = 11;
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.createGraphics();
    ColorModel colorModel = bi.getColorModel();

    g.setColor(Color.WHITE);/* ww w .  j  a  va2 s . c  o m*/
    g.fillRect(0, 0, width, height);

    g.setColor(Color.BLACK);
    g.setFont(this.dedWindow.diagramFont);
    g.drawString("A", 0, 10);

    // Print that glyph as a string.
    StringBuilder sb = new StringBuilder();
    for (int y = 0; y < height; y++) {
        int bits = 0;
        for (int x = 0; x < width; x++) {
            int pixel = bi.getRGB(x, y);
            int red = colorModel.getRed(pixel);
            int green = colorModel.getGreen(pixel);
            int blue = colorModel.getBlue(pixel);
            int alpha = colorModel.getAlpha(pixel);
            boolean isWhite = (red == 255 && green == 255 && blue == 255 && alpha == 255);
            boolean isBlack = (red == 0 && green == 0 && blue == 0 && alpha == 255);
            sb.append(
                    isWhite ? "_" : isBlack ? "X" : ("(" + red + "," + green + "," + blue + "," + alpha + ")"));

            bits <<= 1;
            if (!isWhite) {
                bits |= 1;
            }
        }
        sb.append(String.format("  (0x%03X)\n", bits));
    }

    // Also include some of the font metrics.
    FontMetrics fm = g.getFontMetrics();
    sb.append("fm: ascent=" + fm.getAscent() + " leading=" + fm.getLeading() + " charWidth('A')="
            + fm.charWidth('A') + " descent=" + fm.getDescent() + " height=" + fm.getHeight() + "\n");

    String actualGlyph = sb.toString();

    g.dispose();

    // The expected glyph and metrics.
    String expectedGlyph = "_________  (0x000)\n" + "____X____  (0x010)\n" + "___X_X___  (0x028)\n"
            + "___X_X___  (0x028)\n" + "__X___X__  (0x044)\n" + "__X___X__  (0x044)\n" + "__XXXXX__  (0x07C)\n"
            + "_X_____X_  (0x082)\n" + "_X_____X_  (0x082)\n" + "_X_____X_  (0x082)\n" + "_________  (0x000)\n"
            + "fm: ascent=10 leading=1 charWidth('A')=9 descent=3 height=14\n";

    if (!expectedGlyph.equals(actualGlyph)) {
        // Currently, this is known to happen when using OpenJDK 6
        // and 7, with 6 being close to right and 7 being very bad.
        // I also have reports of it happening on certain Mac OS/X
        // systems, but I haven't been able to determine what the
        // important factor there is.
        String warningMessage = "There is a problem with the font rendering.  The glyph "
                + "for the letter 'A' should look like:\n" + expectedGlyph + "but it renders as:\n"
                + actualGlyph + "\n" + "This probably means there is a bug in the TrueType "
                + "font library.  You might try a different Java version.  "
                + "(I'm working on how to solve this permanently.)";
        System.err.println(warningMessage);
        this.log(warningMessage);
        SwingUtil.errorMessageBox(null /*component*/, warningMessage);
    }
}