List of usage examples for java.awt FontMetrics charWidth
public int charWidth(char ch)
From source file:Main.java
public static void main(String args[]) { JFrame f = new JFrame("JColorChooser Sample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(300, 200);//www . j av a2 s . c o m f.setVisible(true); FontMetrics metrics = f.getFontMetrics(f.getFont()); int widthX = metrics.charWidth((int) 'C'); System.out.println(widthX); }
From source file:Main.java
public static void main(String args[]) { JFrame f = new JFrame("JColorChooser Sample"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(300, 200);/* www .j av a 2 s . c o m*/ f.setVisible(true); FontMetrics metrics = f.getFontMetrics(f.getFont()); int widthX = metrics.charWidth('X'); System.out.println(widthX); }
From source file:Main.java
public static void setTabs(JTextPane textPane, int charactersPerTab) { FontMetrics fm = textPane.getFontMetrics(textPane.getFont()); int charWidth = fm.charWidth('w'); int tabWidth = charWidth * charactersPerTab; TabStop[] tabs = new TabStop[5]; for (int i = 0; i < tabs.length; i++) { int tab = i + 1; tabs[i] = new TabStop(tab * tabWidth); }/* w ww. j ava2s . c om*/ TabSet tabSet = new TabSet(tabs); SimpleAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setTabSet(attributes, tabSet); int length = textPane.getDocument().getLength(); textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false); }
From source file:Main.java
/** * Paints string with underlined character at the specified index. * * @param g graphics context * @param text painted text/* w ww . j a v a 2s .c om*/ * @param underlinedIndex underlined character index * @param x text X coordinate * @param y text Y coordinate */ public static void drawStringUnderlineCharAt(final Graphics g, final String text, final int underlinedIndex, final int x, final int y) { // Painting string drawString(g, text, x, y); // Painting character underline if (underlinedIndex >= 0 && underlinedIndex < text.length()) { final FontMetrics fm = g.getFontMetrics(); g.fillRect(x + fm.stringWidth(text.substring(0, underlinedIndex)), y + fm.getDescent() - 1, fm.charWidth(text.charAt(underlinedIndex)), 1); } }
From source file:org.mili.core.graphics.GraphicsUtil.java
/** * Prints a character image in defined font in a file. * * @param dir directory.// w w w .j av a 2 s . c o m * @param fn filename. * @param font font. * @param c character to print in file. * @param mx character size x. * @param my character size y. * @throws IOException if io exception occurs. */ public static void writeChar(File dir, String fn, Font font, char c, int mx, int my) throws IOException { BufferedImage bi = new BufferedImage(mx, my, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bi.createGraphics(); g.setFont(font); FontMetrics fm = g.getFontMetrics(); int fh = fm.getHeight(); int cw = fm.charWidth(c); int asc = g.getFontMetrics().getAscent(); int x0 = mx / 2 - cw / 2; int y0 = my / 2 - fh / 2 + asc; g.drawString(String.valueOf(c), x0, y0); g.dispose(); File f = new File(dir, fn); GraphicsUtil.writeImage(f, bi); }
From source file:Main.java
/** * Returns a string abbreviated according to the length of the available space * in a component./*from www .j ava 2 s.c om*/ * @param str A string which may need abbreviating. * @param component The component the string will be rendered in. * @return a string abbreviated according to the length of the available space */ public static String abbreviate(String str, JComponent component) { String result = ""; if (component != null) { Graphics g = component.getGraphics(); FontMetrics fm = g.getFontMetrics(component.getFont()); int stringSize = SwingUtilities.computeStringWidth(fm, str); final int border = 48; int availableWidth = component.getWidth() - border; if (stringSize > availableWidth) { final int avCharWidth = fm.charWidth('x'); final int alwaysChop = 5; final int charsToChop = alwaysChop + ((stringSize - availableWidth) / avCharWidth); final int leftPos = (str.length() - charsToChop) / 2; final int maxLength = str.length() - charsToChop; final int left = leftPos > 0 ? leftPos : 0; final int len = maxLength > left ? maxLength : left + 1; result = abbreviate(str, left, len); } else { result = str; } } return result; }
From source file:Main.java
public static String getClippedText(String text, FontMetrics fm, int maxWidth) { if ((text == null) || (text.length() == 0)) { return ""; }/*from ww w. jav a 2 s . co m*/ int width = SwingUtilities.computeStringWidth(fm, text); if (width > maxWidth) { int totalWidth = SwingUtilities.computeStringWidth(fm, ELLIPSIS); for (int i = 0; i < text.length(); i++) { totalWidth += fm.charWidth(text.charAt(i)); if (totalWidth > maxWidth) { return text.substring(0, i) + ELLIPSIS; } } } return text; }
From source file:org.geopublishing.atlasViewer.GpCoreUtil.java
public static void setTabs(final JTextPane textPane, final int charactersPerTab) { final FontMetrics fm = textPane.getFontMetrics(textPane.getFont()); final int charWidth = fm.charWidth('w'); final int tabWidth = charWidth * charactersPerTab; final TabStop[] tabs = new TabStop[10]; for (int j = 0; j < tabs.length; j++) { final int tab = j + 1; tabs[j] = new TabStop(tab * tabWidth); }/*from ww w. j a v a 2 s. c om*/ final TabSet tabSet = new TabSet(tabs); final SimpleAttributeSet attributes = new SimpleAttributeSet(); StyleConstants.setTabSet(attributes, tabSet); final int length = textPane.getDocument().getLength(); textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false); }
From source file:ala.soils2sat.DrawingUtils.java
/** * Clips the passed in String to the space provided. NOTE: this assumes the string does not fit in the available space. * * @param c/*from w w w. ja v a 2 s .c om*/ * JComponent that will display the string, may be null * @param fm * FontMetrics used to measure the String width * @param string * String to display * @param availTextWidth * Amount of space that the string can be drawn in * @return Clipped string that can fit in the provided space. */ public static String clipString(JComponent c, FontMetrics fm, String string, int availTextWidth) { // c may be null here. String clipString = "..."; int width = stringWidth(c, fm, clipString); // NOTE: This does NOT work for surrogate pairs and other fun // stuff int nChars = 0; for (int max = string.length(); nChars < max; nChars++) { width += fm.charWidth(string.charAt(nChars)); if (width > availTextWidth) { break; } } string = string.substring(0, nChars) + clipString; return string; }
From source file:org.apache.ofbiz.common.CommonEvents.java
public static String getCaptcha(HttpServletRequest request, HttpServletResponse response) { try {// w w w . ja v a 2s. c o m Delegator delegator = (Delegator) request.getAttribute("delegator"); final String captchaSizeConfigName = StringUtils.defaultIfEmpty(request.getParameter("captchaSize"), "default"); final String captchaSizeConfig = EntityUtilProperties.getPropertyValue("captcha", "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", "captcha.code_length", 6); final char[] availableChars = EntityUtilProperties .getPropertyValue("captcha", "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"; }