Calculate the display width of a string in Java

How to calculate the length (in pixels) of a string in Java?

Preferable without using Swing.

EDIT: I would like to draw the string using the drawString() in Java2D and use the length for word wrapping.


Asked by: Nicole993 | Posted: 28-01-2022






Answer 1

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

Answered by: Patrick310 | Posted: 01-03-2022



Answer 2

It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment.

I have tested this in a web servlet and it does calculate the text width.

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

...

String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());

Add the necessary values to these dimensions to create any required margin.

Answered by: Alina222 | Posted: 01-03-2022



Answer 3

Use the getWidth method in the following class:

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;

class StringMetrics {

  Font font;
  FontRenderContext context;

  public StringMetrics(Graphics2D g2) {

    font = g2.getFont();
    context = g2.getFontRenderContext();
  }

  Rectangle2D getBounds(String message) {

    return font.getStringBounds(message, context);
  }

  double getWidth(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getWidth();
  }

  double getHeight(String message) {

    Rectangle2D bounds = getBounds(message);
    return bounds.getHeight();
  }

}

Answered by: Brianna365 | Posted: 01-03-2022



Answer 4

And now for something completely different. The following assumes arial font, and makes a wild guess based on a linear interpolation of character vs width.

// Returns the size in PICA of the string, given space is 200 and 'W' is 1000.
// see https://p2p.wrox.com/access/32197-calculate-character-widths.html

static int picaSize(String s)
{
    // the following characters are sorted by width in Arial font
    String lookup = " .:,;'^`!|jl/\\i-()JfIt[]?{}sr*a\"ce_gFzLxkP+0123456789<=>~qvy$SbduEphonTBCXY#VRKZN%GUAHD@OQ&wmMW";
    int result = 0;
    for (int i = 0; i < s.length(); ++i)
    {
        int c = lookup.indexOf(s.charAt(i));
        result += (c < 0 ? 60 : c) * 7 + 200;
    }
    return result;
}

Interesting, but perhaps not very practical.

Answered by: Agata164 | Posted: 01-03-2022



Answer 5

I personally was searching for something to let me compute the multiline string area, so I could determine if given area is big enough to print the string - with preserving specific font.

private static Hashtable hash = new Hashtable();
private Font font;
private LineBreakMeasurer lineBreakMeasurer;
private int start, end;

public PixelLengthCheck(Font font) {
    this.font = font;
}

public boolean tryIfStringFits(String textToMeasure, Dimension areaToFit) {
    AttributedString attributedString = new AttributedString(textToMeasure, hash);
    attributedString.addAttribute(TextAttribute.FONT, font);
    AttributedCharacterIterator attributedCharacterIterator =
            attributedString.getIterator();
    start = attributedCharacterIterator.getBeginIndex();
    end = attributedCharacterIterator.getEndIndex();

    lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,
            new FontRenderContext(null, false, false));

    float width = (float) areaToFit.width;
    float height = 0;
    lineBreakMeasurer.setPosition(start);

    while (lineBreakMeasurer.getPosition() < end) {
        TextLayout textLayout = lineBreakMeasurer.nextLayout(width);
        height += textLayout.getAscent();
        height += textLayout.getDescent() + textLayout.getLeading();
    }

    boolean res = height <= areaToFit.getHeight();

    return res;
}

Answered by: Audrey561 | Posted: 01-03-2022



Similar questions

java - Calculate and display frame per second of a game


java - Calculate the sum of fields and display for each amount

There is a program that builds a matrix of 15x20, and sort fields from smallest to largest amount in their field. Help implement a function that displays the sum of each field. Java code: import javax.swing.JApplet; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.JButton; i...


java - How to calculate the sum of number in radio button that user click and then display that sum in another layout?

I want to make a quiz app that can calculate the sum of the number in radio button that user click. How to caluclate the sum and how can I display the result in another layout after user click the button to generate the result? Question page Result page Here...


Trying to create a menu in java to calculate and display information about a circle

I'm pretty new to java and I've been working through some questions and have been mostly okay but I've had a lot of trouble with this question which asks me to create a menu to find out and display various information about a circle. My code is as follows: import java.util.Scanner; public class Circle2 { public static void main(String[] args) { final double pi = 3.1416; Scanner values...


java - How to display and calculate random numbers in a JLabel?

I am trying to create a program where I could calculate 2 randomly generated numbers and display them in a JLabel. The program is successfully displaying random numbers in a JLabel but it only calculates the first set of numbers that have been generated. I want it to be able to calculate all the sets of numbers being generated randomly. Random dice = new Random(); boolean sol...


date - Calculate elapsed time in Java / Groovy

I have... Date start = new Date() ... ... ... Date stop = new Date() I'd like to get the years, months, days, hours, minutes and seconds ellapsed between these two dates. -- I'll refine the question. I just want to get the elapsed time, as an absolute measure, that is without taking into account leap years, the days of each month, etc. Thus I think it's i...


datetime - Is there an easy way to Calculate and format time/date intervals in java?

I'm familiar with the the date and time classes in the JDK and their associated formatting methods. I may be blind, but I cannot find an equivalent set of classes for processing time intervals. For example, I would like to display the number of days for a given long value of milliseconds. I realize that the method to do these conversions is quite simple, however when you factor in internationalization and localization supp...


date - How can I calculate a time span in Java and format the output?

I want to take two times (in seconds since epoch) and show the difference between the two in formats like: 2 minutes 1 hour, 15 minutes 3 hours, 9 minutes 1 minute ago 1 hour, 2 minutes ago How can I accomplish this??


Calculate distance in meters when you know longitude and latitude in java

This question already has answers here:


Java date iterator factory, with rules specifying how to calculate the intervals

I am looking for a Java class where I can specify a set of date rules, such as "every 3rd sunday" and "the first occurrence of a monday every second month". I want to be able to get something like an infinite iterator out of it (.next() would return the next date matching the rules set). I think I'd be able to build it myself - but calendars are a hassle, and it feels like something similar should exist already. I ...


date - How do I calculate someone's age in Java?

I want to return an age in years as an int in a Java method. What I have now is the following where getBirthDate() returns a Date object (with the birth date ;-)): public int getAge() { long ageInMillis = new Date().getTime() - getBirthDate().getTime(); Date age = new Date(ageInMillis); return age.getYear(); } But since getYear() is deprecated I'm wondering if there is a bett...


java - calculate frequency on certain range

I have maths problem ... (at the moment i solved it using manual iteration which is pretty slow) ... For example if an employee got paid weekly (it can be fortnightly / every 2 weeks and monthly) with certain date (let's call the employee got paid every tuesday and for monthly the employee paid on certain date). I have date range between 10th August 2009- 31 December 2009, now how to get frequency the empl...


c++ - Calculate minimum area rectangle for a polygon

I have a need to calculate the minimum area rectangle (smallest possible rectangle) around the polygon. The only input i have is the number of points in polygon. I have the co-ordinates of the points also.


java - why these two sources calculate different sha-1 sums

The following snippets are both supposed to calculate sha-1 sum. But for the same file they calculate different sha-1 sums. //snippet1 byte[] byteArr = new byte[(int) uploadedFile.getLength()]; try { stream = new BufferedInputStream(uploadedFile.getInputStream()); stream.read(byteArr); stream.close(); } catch (IOException e) { e.printStackTrace(); } md = MessageDigest.getInstance("SHA-1"); byte[] sha...


java - How to calculate the font's width?

I am using java to draw some text, but it is hard for me to calculate the string's width. for example: zheng中国... How long will this string occupy?






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top