Example usage for java.awt FontMetrics stringWidth

List of usage examples for java.awt FontMetrics stringWidth

Introduction

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

Prototype

public int stringWidth(String str) 

Source Link

Document

Returns the total advance width for showing the specified String in this Font .

Usage

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFUInt64ColumnCellRenderer.java

public void paint(Graphics g) {
    if (g == null) {
        return;//  w w w  . j a va  2  s  .c  om
    }
    Rectangle bounds = getBounds();
    g.setColor(getBackground());
    g.fill3DRect(0, 0, bounds.width, bounds.height, true);
    g.setColor(getForeground());
    String str;
    if (value instanceof BigDecimal) {
        BigDecimal val = (BigDecimal) value;
        Format fmt = getDefaultFormat();
        str = fmt.format(val);
    } else if (value instanceof String) {
        str = (String) value;
    } else {
        str = null;
    }
    if (str != null) {
        int firstNewline = str.indexOf('\n');
        if (firstNewline < 0) {
            firstNewline = str.indexOf('\r');
            if (firstNewline < 0) {
                firstNewline = str.indexOf('\f');
                if (firstNewline < 0) {
                    firstNewline = str.length();
                }
            }
        }
        String firstLine = str.substring(0, firstNewline);
        FontMetrics fm = g.getFontMetrics();
        int ascent = fm.getAscent();
        int leading = fm.getLeading();
        int width = fm.stringWidth(firstLine);
        int x = (bounds.width - 8) - width;
        g.drawString(firstLine, x, leading + ascent + 4);
    }
}

From source file:CalIcon.java

public void paint(Graphics g) {
    Calendar myCal = Calendar.getInstance();
    StringBuffer sb = new StringBuffer();
    sb.append(tf.format(myCal.get(Calendar.HOUR)));
    sb.append(':');
    sb.append(tflz.format(myCal.get(Calendar.MINUTE)));
    sb.append(':');
    sb.append(tflz.format(myCal.get(Calendar.SECOND)));
    String s = sb.toString();//from   ww  w.jav  a 2s.  c  o m
    FontMetrics fm = getFontMetrics(getFont());
    int x = (getSize().width - fm.stringWidth(s)) / 2;
    // System.out.println("Size is " + getSize());
    g.drawString(s, x, 10);
}

From source file:ChartPanel.java

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (values == null || values.length == 0)
        return;/*  www .ja  v  a2  s .c om*/
    double minValue = 0;
    double maxValue = 0;
    for (int i = 0; i < values.length; i++) {
        if (minValue > values[i])
            minValue = values[i];
        if (maxValue < values[i])
            maxValue = values[i];
    }

    Dimension d = getSize();
    int clientWidth = d.width;
    int clientHeight = d.height;
    int barWidth = clientWidth / values.length;

    Font titleFont = new Font("SansSerif", Font.BOLD, 20);
    FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);
    Font labelFont = new Font("SansSerif", Font.PLAIN, 10);
    FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);

    int titleWidth = titleFontMetrics.stringWidth(title);
    int y = titleFontMetrics.getAscent();
    int x = (clientWidth - titleWidth) / 2;
    g.setFont(titleFont);
    g.drawString(title, x, y);

    int top = titleFontMetrics.getHeight();
    int bottom = labelFontMetrics.getHeight();
    if (maxValue == minValue)
        return;
    double scale = (clientHeight - top - bottom) / (maxValue - minValue);
    y = clientHeight - labelFontMetrics.getDescent();
    g.setFont(labelFont);

    for (int i = 0; i < values.length; i++) {
        int valueX = i * barWidth + 1;
        int valueY = top;
        int height = (int) (values[i] * scale);
        if (values[i] >= 0)
            valueY += (int) ((maxValue - values[i]) * scale);
        else {
            valueY += (int) (maxValue * scale);
            height = -height;
        }

        g.setColor(Color.red);
        g.fillRect(valueX, valueY, barWidth - 2, height);
        g.setColor(Color.black);
        g.drawRect(valueX, valueY, barWidth - 2, height);
        int labelWidth = labelFontMetrics.stringWidth(names[i]);
        x = i * barWidth + (barWidth - labelWidth) / 2;
        g.drawString(names[i], x, y);
    }
}

From source file:de.iteratec.iteraplan.presentation.dialog.GraphicalReporting.Line.JFreeChartSvgRenderer.java

byte[] renderJFreeChart(JFreeChart chart, float width, float height, boolean naked, Date fromDate, Date toDate)
        throws IOException {
    String svgNamespaceUri = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = SVGDOMImplementation.getDOMImplementation().createDocument(svgNamespaceUri, "svg", null);

    String generatedText = "Generated "
            + DateUtils.formatAsStringToLong(new Date(), UserContext.getCurrentLocale()) + " by "
            + MessageAccess.getStringOrNull("global.applicationname", UserContext.getCurrentLocale()) + " "
            + properties.getBuildId();/*ww w. j av a  2 s.c o m*/
    String drawingInfo = MessageAccess.getStringOrNull("graphicalExport.timeline.drawInfo",
            UserContext.getCurrentLocale()) + ": "
            + DateUtils.formatAsString(fromDate, UserContext.getCurrentLocale()) + " -> "
            + DateUtils.formatAsString(toDate, UserContext.getCurrentLocale());

    SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(doc);
    ctx.setComment(generatedText);
    SVGGraphics2D svgGraphics = new SVGGraphics2D(ctx, false);

    if (!naked) {
        //Render the chart to the SVG graphics object
        chart.draw(svgGraphics, new Rectangle(20, 20, Math.round(width - MARGIN), Math.round(height - MARGIN)));

        //Add logo and generated text
        int widthIntForLogo = Math.round(width + 40 - MARGIN);
        int heightIntForLogo = Math.round(height - MARGIN + 20);

        int xLogoUpperRightCorner[] = { widthIntForLogo - 40, widthIntForLogo, widthIntForLogo,
                widthIntForLogo - 8, widthIntForLogo - 8, widthIntForLogo - 40 };
        int yLogoUpperRightCorner[] = { MARGIN_TOP, MARGIN_TOP, MARGIN_TOP + 40, MARGIN_TOP + 40,
                MARGIN_TOP + 8, MARGIN_TOP + 8 };

        GeneralPath logoUpperRightCorner = new GeneralPath();
        logoUpperRightCorner.moveTo(xLogoUpperRightCorner[0], yLogoUpperRightCorner[0]);
        for (int i = 1; i < xLogoUpperRightCorner.length; i++) {
            logoUpperRightCorner.lineTo(xLogoUpperRightCorner[i], yLogoUpperRightCorner[i]);
        }
        logoUpperRightCorner.closePath();
        svgGraphics.setColor(Color.decode(COLOR_LOGO));
        svgGraphics.fill(logoUpperRightCorner);
        svgGraphics.draw(logoUpperRightCorner);

        int xLogoLowerLeftCorner[] = { MARGIN_LEFT, MARGIN_LEFT + 8, MARGIN_LEFT + 8, MARGIN_LEFT + 40,
                MARGIN_LEFT + 40, MARGIN_LEFT };
        int yLogoLowerLeftCorner[] = { heightIntForLogo, heightIntForLogo, heightIntForLogo + 32,
                heightIntForLogo + 32, heightIntForLogo + 40, heightIntForLogo + 40 };

        GeneralPath logoLowerLeftCorner = new GeneralPath();
        logoLowerLeftCorner.moveTo(xLogoLowerLeftCorner[0], yLogoLowerLeftCorner[0]);
        for (int i = 1; i < xLogoLowerLeftCorner.length; i++) {
            logoLowerLeftCorner.lineTo(xLogoLowerLeftCorner[i], yLogoLowerLeftCorner[i]);
        }
        logoLowerLeftCorner.closePath();
        svgGraphics.setColor(Color.BLACK);
        svgGraphics.fill(logoLowerLeftCorner);
        svgGraphics.draw(logoLowerLeftCorner);

        Font f = new Font(null, Font.ITALIC, 12);
        svgGraphics.setFont(f);
        FontMetrics fontMetrics = svgGraphics.getFontMetrics(f);
        int charsWidthInfo = fontMetrics.stringWidth(drawingInfo);
        svgGraphics.drawString(drawingInfo, width - MARGIN - charsWidthInfo,
                height - MARGIN + MARGIN_DOWN_GENERATED_TEXT);
        int charsWidth = fontMetrics.stringWidth(generatedText);
        svgGraphics.drawString(generatedText, width - MARGIN - charsWidth,
                height - MARGIN + MARGIN_DOWN_GENERATED_TEXT + 20);

    } else {
        chart.draw(svgGraphics,
                new Rectangle(20, 20, Math.round(JFreeChartLineGraphicCreator.DEFAULT_HEIGHT - NAKED_MARGIN),
                        Math.round(JFreeChartLineGraphicCreator.DEFAULT_HEIGHT - NAKED_MARGIN)));
    }

    svgGraphics.setSVGCanvasSize(new Dimension((int) width, (int) height));

    //Convert the SVGGraphics2D object to SVG XML 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Writer out = new OutputStreamWriter(baos, "UTF-8");
    svgGraphics.stream(out, true);
    byte[] originalSvgXml = baos.toByteArray();

    //    return originalSvgXml;
    return addAdditionalAttributes(originalSvgXml);
}

From source file:Main.java

/**
 * Return the preferred size of this component.
 *
 * @return the preferred size of this component.
 *///w  ww. j  a  va  2  s .  c  o m
public Dimension getPreferredSize() {
    if (null == _prefSize) {
        // This was originaly done every time.
        // and the count of instantiated objects was amazing
        _prefSize = new Dimension();
        _prefSize.height = 20;
        FontMetrics fm = getFontMetrics(getFont());
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        _prefSize.width = fm.stringWidth(_fmt.format(cal.getTime()));
        Border border = getBorder();
        if (border != null) {
            Insets ins = border.getBorderInsets(this);
            if (ins != null) {
                _prefSize.width += (ins.left + ins.right);
            }
        }
        Insets ins = getInsets();
        if (ins != null) {
            _prefSize.width += (ins.left + ins.right) + 20;
        }
    }
    return _prefSize;
}

From source file:main.AddNodeDemo.java

@Override
public void init() {

    //create a graph
    Graph<String, Number> ig = Graphs
            .<String, Number>synchronizedDirectedGraph(new DirectedSparseMultigraph<String, Number>());

    ObservableGraph<String, Number> og = new ObservableGraph<String, Number>(ig);
    og.addGraphEventListener(new GraphEventListener<String, Number>() {

        public void handleGraphEvent(GraphEvent<String, Number> evt) {
            System.err.println("got " + evt);

        }//from   w w  w  .ja  va  2s.  c  o  m
    });
    this.g = og;
    //create a graphdraw
    //        layout = new FRLayout2<String,Number>(g);
    //        layout = new SpringLayout<String,Number>(g);
    //        ((FRLayout)layout).setMaxIterations(200);
    layout = new KKLayout<String, Number>(g);

    vv = new VisualizationViewer<String, Number>(layout, new Dimension(600, 600));

    JRootPane rp = this.getRootPane();
    rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);

    getContentPane().setLayout(new BorderLayout());
    getContentPane().setBackground(java.awt.Color.lightGray);
    getContentPane().setFont(new Font("Serif", Font.PLAIN, 12));

    vv.getModel().getRelaxer().setSleepTime(500);
    vv.setGraphMouse(new DefaultModalGraphMouse<Number, Number>());

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<String>());
    vv.setForeground(Color.white);

    FontMetrics fm = vv.getFontMetrics(vv.getFont());
    int width = fm.stringWidth(g.toString());

    Transformer<String, Shape> vertexSize = new Transformer<String, Shape>() {
        public Shape transform(String i) {

            Ellipse2D circle = new Ellipse2D.Double(-20, -20, 40, 40);
            // in this case, the vertex is twice as large                
            return circle;
        }

    };

    //        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller() {
    //            @Override
    //            public String transform(Object v) {
    //
    //                return ((VertexTopology)v).screenName;
    //            }});

    vv.getRenderContext().setVertexShapeTransformer(vertexSize);

    getContentPane().setPreferredSize(new Dimension(1400, 900));
    getContentPane().add(vv);
    switchLayout = new JButton("Switch to SpringLayout");
    //        switchLayout.addActionListener(new ActionListener() {
    //
    //            @SuppressWarnings("unchecked")
    //            public void actionPerformed(ActionEvent ae) {
    //               Dimension d = new Dimension(600,600);
    //                if (switchLayout.getText().indexOf("Spring") > 0) {
    //                    switchLayout.setText("Switch to FRLayout");
    //                    layout = new SpringLayout<String,Number>(g,
    //                        new ConstantTransformer(EDGE_LENGTH));
    //                    layout.setSize(d);
    //                    vv.getModel().setGraphLayout(layout, d);
    //                } else {
    //                    switchLayout.setText("Switch to SpringLayout");
    //                    layout = new FRLayout<String,Number>(g, d);
    //                    vv.getModel().setGraphLayout(layout, d);
    //                }
    //            }
    //        });

    getContentPane().add(switchLayout, BorderLayout.SOUTH);

    timer = new Timer();
}

From source file:edu.csudh.goTorosBank.WithdrawServlet.java

public String writeIntoCheck(String filePath, String username, String theAmount, String amountInWords,
        String dateWrote, String person_payingto, String billType) throws IOException, NullPointerException {

    File blueCheck = new File("blank-blue-check.jpg");
    String pathToOriginal = getServletContext().getRealPath("/" + blueCheck);

    File file = new File(pathToOriginal);
    BufferedImage imageToCopy = null;
    try {/*w ww. j a v a 2s  . com*/
        imageToCopy = ImageIO.read(file);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String amount = theAmount;
    String person_gettingPayed = person_payingto;
    String amountinWords = amountInWords;
    String date = dateWrote;
    String bill_type = billType;

    int w = imageToCopy.getWidth();
    int h = imageToCopy.getHeight();
    BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = img.createGraphics();
    g2d.setColor(g2d.getBackground());
    g2d.fillRect(0, 0, w, h);
    g2d.drawImage(imageToCopy, 0, -100, null);
    g2d.setPaint(Color.black);
    g2d.setFont(new java.awt.Font("Serif", Font.BOLD, 36));
    //g2d.setFont(new Font("Serif", Font.BOLD, 36));

    FontMetrics fm = g2d.getFontMetrics();
    int x = img.getWidth() - fm.stringWidth(amount) - 100;
    int y = fm.getHeight();
    g2d.drawString(amount, x - 70, y + 335);
    g2d.drawString(person_gettingPayed, x - 800, y + 329);
    g2d.drawString(amountinWords, x - 940, y + 390);
    g2d.drawString(date, x - 340, y + 245);
    g2d.drawString(bill_type, x - 900, y + 530);

    String signature = "Use The Force";
    g2d.setFont(new java.awt.Font("Monotype Corsiva", Font.BOLD | Font.ITALIC, 36));
    g2d.drawString(signature, x - 340, y + 530);
    g2d.dispose();
    /*write check to file*/
    String filename = fileNameGenerator(username);
    String fullname = filePath + "_" + filename + ".jpg";
    ImageIO.write(img, "jpg", new File(fullname));
    return fullname;
}

From source file:ucar.unidata.idv.control.chart.TrackSegment.java

/**
 * Draws the wayPoint./*from   ww  w  .  j  av a  2  s  . co m*/
 *
 * @param g2  the graphics device.
 * @param plot  the plot.
 * @param dataArea  the data area.
 * @param domainAxis  the domain axis.
 * @param rangeAxis  the range axis.
 * @param rendererIndex  the renderer index.
 * @param info  an optional info object that will be populated with
 *              entity information.
 */
public void draw(Graphics2D g2, XYPlot plot, Rectangle2D dataArea, ValueAxis domainAxis, ValueAxis rangeAxis,
        int rendererIndex, PlotRenderingInfo info) {
    super.setGraphicsState(g2);

    if (!getPlotWrapper().okToDraw(this)) {
        return;
    }
    WayPoint leftWayPoint = getLeft();
    WayPoint rightWayPoint = getRight();
    g2.setStroke(new BasicStroke());
    int x1 = leftWayPoint.getXFromValue(dataArea, domainAxis);
    int x2 = rightWayPoint.getXFromValue(dataArea, domainAxis);
    int top = (int) (dataArea.getY());
    int bottom = (int) (dataArea.getY() + dataArea.getHeight());
    FontMetrics fm = g2.getFontMetrics();
    int width = fm.stringWidth(getName());
    int height = fm.getAscent() + fm.getDescent();
    if (getSelected()) {
        g2.setColor(Color.red);
    } else {
        g2.setColor(Color.black);
    }
    //      int y = bottom-3;
    y = top - 2;
    int textLeft = x1 + (x2 - x1) / 2 - width / 2;
    g2.drawString(getName(), textLeft, y);
    g2.setStroke(new BasicStroke(2.0f));
    g2.drawLine(x1, top + 1, x2, top + 1);
    g2.setStroke(new BasicStroke(1.0f));
    g2.setColor(Color.gray);
    g2.drawLine(x1, top, x1, bottom - WayPoint.ANNOTATION_WIDTH);
    g2.drawLine(x2, top, x2, bottom - WayPoint.ANNOTATION_WIDTH);
}

From source file:net.sourceforge.msscodefactory.cflib.v1_11.CFLib.Swing.CFNumberColumnCellRenderer.java

public void paint(Graphics g) {
    if (g == null) {
        return;/*w w  w.j  a v  a 2  s.c  o  m*/
    }
    Rectangle bounds = getBounds();
    g.setColor(getBackground());
    g.fill3DRect(0, 0, bounds.width, bounds.height, true);
    g.setColor(getForeground());
    String str;
    if (value instanceof BigDecimal) {
        BigDecimal val = (BigDecimal) value;
        Format fmt = getNumberFormat(digits, precis);
        str = fmt.format(val);
    } else if (value instanceof String) {
        str = (String) value;
    } else {
        str = null;
    }
    if (str != null) {
        int firstNewline = str.indexOf('\n');
        if (firstNewline < 0) {
            firstNewline = str.indexOf('\r');
            if (firstNewline < 0) {
                firstNewline = str.indexOf('\f');
                if (firstNewline < 0) {
                    firstNewline = str.length();
                }
            }
        }
        String firstLine = str.substring(0, firstNewline);
        FontMetrics fm = g.getFontMetrics();
        int ascent = fm.getAscent();
        int leading = fm.getLeading();
        int width = fm.stringWidth(firstLine);
        int x = (bounds.width - 8) - width;
        g.drawString(firstLine, x, leading + ascent + 4);
    }
}

From source file:org.cybercat.automation.addons.common.ScreenshotManager.java

public BufferedImage applySubs(BufferedImage image, String text) {
    Graphics2D g2 = image.createGraphics();
    g2.setFont(font);/*from   www . j av a 2s . co m*/

    int height = image.getHeight();
    int width = image.getWidth();

    g2.setColor(fontColor);

    String[] subs = text.split("\n");
    FontMetrics fMetrics = g2.getFontMetrics();
    int lineHeight = fMetrics.getHeight();
    int lineWidth;
    for (int i = subs.length; i > 0; i--) {
        lineWidth = fMetrics.stringWidth(subs[i - 1]);
        int y = height - bottomOffset - ((subs.length - i) * (lineHeight + lineOffset));
        int x = (width / 2) - (lineWidth / 2);
        g2.drawString(subs[i - 1], x, y);
    }
    g2.dispose();
    return image;
}