Width of a string in pixels

is it possible to get the width of a given string in pixels, if so how to do it ??

Yes, and you can get the FontMetrics from java.awt.Component (i.e. from all the awt and swing components) with getFontMetrics()

Similar Messages

  • Getiing length of String in pixels.

    I need to set up legth of combobox depending on length of strings in it. Can I get length of String in pixels?

    You should use the getFontMetrics() method of the Graphics object used by the painting methods of the combo.
    Then the stringWidth(String) method of the given font metrics should give you the needed width.
    Just take care of the fact that the combo must be realized (set visible or packed) for this to work.

  • Length of a string in pixel

    Hello,
    I am programming a servlet which produces html pages. The page contains a table with more than one column. The columns have a static width of 200 pixel. Now, I want to put some strings into the cells of the table. Depending on the width in pixel, there shall be one ore more cells in a row reserved for one string. How do I know the width of a string in the browser in pixel?
    My idea was, to create a Label within the java-servlet with the right font and fontsize. Then I can get the length in pixel:
    pixellength = testLabel.getFontMetrics(theFont).stringWidth("string to measure");
    That works very well, if the Server has a GUI. If not, the following exception occurs:
    java.lang.NoClassDefFoundError at
    java.lang.Class.forName0(Native Method) at
    java.lang.Class.forName(Class.java:130) at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:62) at
    java.awt.Font.initializeFont(Font.java:310) at
    java.awt.Font.(Font.java:346) at
    The servlet should work on non-GUI servers as well! What can I do now? Any ideas?

    Hi!
    I don't really know if I'm right on this, but:
    If U use nonproportional fonts (like courier) can't U calculate it by multipling the fontsize (which is in pixels) by the stringsize (number of characters)? i.e.: "Teststring" in fontsize 15 would be 150 pixels wide?
    Thomas.

  • Please Help!! How to get the width of the String for print out?

    Hi there,
    I need to do some printing in my application. I just want to know how can I get the width of the string when it is printed on the paper.
    I have tried to use the following code to get the width
    Rectangle2D rec = font.getStringBounds(str, new FontRenderContext(null, true, true));
    double width = rec.getWidth();
    however, the width I got from that function is not correct (the returned width is longer than the printed one)
    Does anyone know how to solve this problem?
    Thank you and Happy New Year !

    hi,
    The getFontMetrics(Font) is also defined in the Component class and therefore you can retrieve it even if you dont override the paint method.
    try the following (provided ur code extends some class that extends Component indirectly)
    FontMetrics f = this.getFontMetrics(this.getFont());
    int width = f.stringWidth(str); //str is the String for which u need to check the width.
    hope this was useful
    happy holidayz

  • Find the length of a string in pixels

    Hello all,
    Wondering if there's a way in PowerShell to find the length of a given string in pixels?

    That would depend on the font used to draw it, including size, bold / italic, etc.  Assuming you know those things, there's a TextRenderer.MeasureText method in the Windows Forms library:
    $string = 'This is my string. There are many like it, but this one is mine.'
    $font = New-Object System.Drawing.Font('Arial', 12, [System.Drawing.FontStyle]'Bold, Italic')
    $size = [System.Windows.Forms.TextRenderer]::MeasureText($string, $font)
    $size.Width

  • GrabFrame() to return a string of pixel information?

    Hi everyone,
    Basically what im looking for is creating a 2d array of values(but id be happy with a string) corrosponding to each of the 320*240 pixels of my camera. At the moment i can get back an awt image using:
    Buffer buf = frameGrabber.grabFrame();
    Image img = (new BufferToImage((VideoFormat) buf.getFormat()).createImage(buf));
    I would of thought that i should meerly use the toString() method. But if i toString() buf i get:
    javax.media.Buffer@22c95b
    and if i toString() img i get:
    BufferedImage@22c95b: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 320 height = 240 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
    If anyone could help, and point me in the direction of the right method to use, i would be greatly appreciative.
    Thanks.

    You will need integer values from an image to do anything meaningful with the data. Something like this -
    int redValues = new int[imageWidth * imageHeight];
    int greenValues  = new int[imageWidth * imageHeight];
    int blueValues  = new int[imageWidth * imageHeight];
    int alphaValues  = new int[imageWidth * imageHeight];
    int counter = 0;
    public void grabEveryPixelInThe Image(Image img, int x, int y, int w, int h) {
            int[] pixels = new int[w * h];
            PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
            try {
                pg.grabPixels();
            } catch (InterruptedException e) {
                System.err.println("interrupted waiting for pixels!");
                return;
            if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
                System.err.println("image fetch aborted or errored");
                return;
            for (int j = 0; j < h; j++) {
                for (int i = 0; i < w; i++) {
                    doOnePixel(pixels[j * w + i]);
    public void doOnePixel( int pixel) {
            int alpha = (pixel >> 24) & 0xff;
            int red   = (pixel >> 16) & 0xff;
            int green = (pixel >>  8) & 0xff;
            int blue  = (pixel      ) & 0xff;
           redValues[ counter] = red ;
           greenValues [ counter] = green ;
           blueValues  [ counter] = blue ;
           AlphaValues [ counter ] = alpha ;
           counter++;
    }regards

  • HTML Report Viewer width changes from percent to pixel after postback

    Post Author: MikeDymond
    CA Forum: General
    Because of the page layout that the report needs to fit into I need to have the ReportViewer width set to 100% (that is 100% of a table cell, embedded within a complex web page). When you first view the page it looks fine, the ReportViewer is correctly set to 100% and fill the space it should. When you then hit the next page button it causes the page to refresh but this time the ReportViewer width is not set correctly. Looking at the code I can see that the relevant line in the HTML is:        <div id="cridcontainerCrystalReportsViewer" style="width: 100%; height: 712px; position:relative">and is correct when you first load the page. However after the Postback it is changed to:        <div id="cridcontainerCrystalReportsViewer" style="width: 100px; height: 408px; position:relative">and hence the page does not display as it should.Even if I force that value to be set in code every time the page is shown it still does not work if it is set to a percentage. If I force it to be set to 500 pixels it works as expected and the viewer is set to 500 pixels wide both before and after the postback.        <div id="cridcontainerCrystalReportsViewer" style="width: 500px; height: 408px; position:relative"> However that is not what I need to make the page look as it should. Anyone got any ideas? Is this a bug in the Viewer?Cheers Mike

    You talking here only about textboxes, what about the other controls in your form(dropdownlists, checboxes....)? How you will be validating the data on these forms? What if you want to implement server side functionality behind?. I'm asking these question
    just to see if you planned well for your idea. I guess you're going into this because you want to runaway of generating many forms via asp.net, is this correct?.
    Another options can be:
    Create forms that are generated on runtime based on your datasource, I've done this before but there was a specific DB design for that. Here you can read your DB and based on you can create the different types of asp.net controls, in addition to calling
    sever side controls and validation.
    The second option is to have a look at the InfoPath product, its mainly used for Sharepoint but not sure for asp.net.
    Fouad Roumieh

  • Getting the width of a String, or centering it within the Applet.

    Hello,
    I want to get a String within the center of my 2D Applet, so I'm wondering if it's possible to get the width (and height) of the String in numbers, or even if it's possible to center like Microsof Word does. If one of the two is possible, please tell it me :)
    Thanks
    PS: I use fonts and a size for the font, could this create problems?
    Edited by: The_Pointer on Mar 27, 2009 3:34 PM
    Edited by: The_Pointer on Mar 27, 2009 3:34 PM

    Can someone explain the
    Graphics.getFontMetrics()
    x = (Component.getWidth() - Fontmetrics.stringWidth()) / 2 a little bit more please?
    Since I get the following errors
    C:\Documents and Settings\Robert van der Pijl\Bureaublad\Clock\clockApplet.java:66: non-static method getFontMetrics() cannot be referenced from a static context
              Graphics.getFontMetrics();
                      ^
    C:\Documents and Settings\Robert van der Pijl\Bureaublad\Clock\clockApplet.java:67: x is not public in java.awt.Component; cannot be accessed from outside package
              x = (Component.getWidth() - Fontmetrics.stringWidth()) / 2;
              ^
    C:\Documents and Settings\Robert van der Pijl\Bureaublad\Clock\clockApplet.java:67: non-static method getWidth() cannot be referenced from a static context
              x = (Component.getWidth() - Fontmetrics.stringWidth()) / 2;
                            ^
    C:\Documents and Settings\Robert van der Pijl\Bureaublad\Clock\clockApplet.java:67: cannot find symbol
    symbol  : variable Fontmetrics
    location: class clockApplet
              x = (Component.getWidth() - Fontmetrics.stringWidth()) / 2;
                                          ^
    4 errors

  • Calculating Height and Width of Text String in 6.1

    We have a vi that uses a CIN. It takes in a specified font and string
    and x,y origin and calculates the rectangular area of the given text.
    We have been using this VI since LabVIEW 4. Unfortunately, it will not
    work in LV6.1 and causes the compatexport.cpp error documented at NI.
    It works in 6.0.2, but not in 6.1. I believe that this VI was
    downloaded from somewhere, but the name was changed long ago. I'm
    wondering if anyone has a simiar VI that works with LV 6.1.
    When I choose the create .c file I get:
    * CIN source file
    #include "extcode.h"
    * typedefs
    typedef struct {
    LStrHandle Font_Name_;
    int16 Size;
    LVBoolean Strikeout_;
    LVBoolean Italic_;
    LVBoolean Underline_;
    LVBoolean Outline_;
    LVBool
    ean Shadow_;
    LVBoolean Bold_;
    uInt16 desired_font_application_;
    } TD1;
    typedef struct {
    int16 horizontal;
    int16 vertical;
    } TD2;
    CIN MgErr CINRun(LStrHandle text, TD1 *_user_specified_font_, int32
    *var3, TD2 *origin_0_0_);
    CIN MgErr CINRun(LStrHandle text, TD1 *_user_specified_font_, int32
    *var3, TD2 *origin_0_0_) {
    /* ENTER YOUR CODE HERE */
    return noErr;

    There is a vi in the picture library called "Get Text Rect.vi" that will give you a cluster of the four points that make up the rectangle around a given text string with the provided font. I'm attaching a small example that demonstrates this.
    Brian
    Attachments:
    TextRect.vi ‏47 KB

  • Calculate string CPI (length of string in pixel)

    Word-wrap position is at the moment done in SAP via length of string (count of letters) via function u201CRKD_WORD_WRAPu201D. But this is counting number of char, this give the problem that different font type and size give different word-wrap position ! -> We need to calculate if possible the word-wrap position via the relative length of text u2013 I tried to find some on SDN and Internet, the only thing I can find is some functionality in JAVA u2026
    Can any one help me how to calculate the length of a string using font type and hight of font... as we use truetype font as arial the length of letter "i" is not the same as 'X' ...
    Best regards Jørgen Jensen

    My problem is not to do the wordwrap, my problem is to find the right position as the length of 'i' is not the same length of 'X'
    example:
    iiiiiiiiii (10)
    XXXXXXXXXX(10)
    must be something like this:
    iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii(wordwrap position 35)
    XXXXXXXXXX(Wordwrap position 10)
    I need a way to find the length of a charactor in a given font and size.
    Best regards Jørgen Jensen

  • Hi quick question on Muse mobile pixel size. Do use the 380 pixel width or resize to 640 pixel width when setting up my mobile design, thank you Guy.

    So watched videos which say different. Just need the right start, thank you.

    So watched videos which say different. Just need the right start, thank you.

  • String width in pixels

    Hi All,
    I'm making a small bar chart program that needs to print the bar values at the very end of the bar.
    Is there a way to determine the width of a string in pixels given it's font and length in characters?
    Basically, I'm trying to get the very last character of the value string to be right aligned with the bar itself without having it run off the edge or be too far towards the center of the bar.
    Also, I don't suppose there is a way to print strings leftward instead of rightward?? No no, of course not, I'm just being silly ;) right?
    Thanks for the help
    Marcos

    Anybody ever hear of StringBuffer???
    Fair enough and yes, yes I have thank you -though I feel it is often better for the newbie to see the process manually and if they study this kinfd of thing then they may learn to work stuff out for themselves when they need to implement their own algorithm.
    This - Snr whoIsFred - is what makes a programmer,
    - knowing how to manipulate your data types to make things work
    - it is not about knowing the API's off by heart (though that can help)
    - knowing how to read and utilise the java API docs is the real key
    I think what was posted therefore is moare beneficial than StringBuffer(aString).reverse()

  • Measuring string bounds in headless mode on a server?

    I have a problem with calculating screen string width for the browser client.
    I'm outputting a stream of content type application/vnd.ms-excel and sending back an XML spreadsheet. (No complaints about using Mc$oft products, it's what's needed!)
    Excel does not autosize columns which contain string data, so the text columns are the standard Excel width, and the text is wrapped onto about 7 lines. See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnexcl2k2/html/odc_xmlss.asp for details of the XML format.
    Excel does allow you to specify the with of a column in points, so I was using the awt Font classes to calculate the string bounds in pixels. I explicitly set the resolution to be used to 72dpi by creating a FontRenderContext with an AffineTransform with a scaling factor of (1.0, 1.0), so that asking the pixel width, gets the point width.
    This worked fine testing it on my windoze machine, but on the Unix server, it's obviously running in headless mode, and anyway, it doesn't have the Arial font which I'm specifying in my spreadsheet as the font to use.
    Is there any way of calculating the width of a string in points knowing its font and the point size of the font? You shouldn't need a graphcs environment, just the font information. I have all the .TTF files, I could copy them to the Unix machine if Java could use them and do the calculation.
    I hate leaving the user interface looking so shoddy with wrong sized columns!
    It SHOULD have worked in a headless environment according to http://java.sun.com/j2se/1.4.2/docs/guide/awt/AWTChanges.html#headless and we are on version 1.4.2_01. It actually blew up in awt code:
    java.lang.NoClassDefFoundError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:141)
         at java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment(GraphicsEnvironment.java:62)
         at java.awt.Font.initializeFont(Font.java:308)
         at java.awt.Font.<init>(Font.java:344)That's when I'm trying to instantiate a new Font("Arial", Font.PLAIN, 10);I've looked at the FOP project wondering whether that has a solution but it's a huge, confusing thing. There must be a way. Can anyone help?

    When you say "unix doesn't have Arial" you obviously aren't using Solaris where Arial most certainly
    ships and is in fact the main font used to support dialog & sanserif.
    There are numerous APIs to calculate the width of a string in pixels, depending on whether
    you want the integer metrics, fp metrics , logical bounds, pixel bounds (which guarantees to enclose
    every pixel if you correctly specify the graphics/FRC)
    Every single one of these works in headless mode.
    Even the most simple-minded FontMetrics.stringWidth(String) call should be good enough
    for your requirements.
    The error you show looks like you have a misconfigured environment.. It can't find
    the correct implementation class of GraphicsEnvironment which is nothing to do with
    fonts. Moreover this DOES work for me :
    import java.awt.*;
    public class Arial {
    public static void main(String args[]) {
    Font arial = new Font("Arial", Font.PLAIN, 10);
    System.out.println(arial);
    % java -version
    java version "1.4.2_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_01-b06)
    Java HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)
    % java -Djava.awt.headless=true Arial
    java.awt.Font[family=Arial,name=Arial,style=plain,size=10]
    QED.
    -Phil.

  • Getting the Bounds of a String in a nonGui App.

    Hi Guys,
    I want to use the getStringBounds method of the FontMetrics object and for accessing the FontMetrics instance, I need to have a gui (in the paintcomponent method). Since I'm working on a commandline application, how can I obtain the FontMetrics instance ?
    I tried the following for returning the width of a string in pixels and it
    returned zero ?!!!.
    Toolkit.getDefaultToolkit ().getFontMetrics ( new Font ( "arial", 12, Font.PLAIN ) ).stringWidth ( "Hello" );
    I appreciate your comments :-)
    Ali Salehi

    Thanks for your answer,
    The program is not going to write anything in console. It generates SVG files
    which contains the figures. For putting a multi-lined text in a
    nice looking rectangle, I need to set the size of the rectangle in advance.
    And for setting the size of the rectangle, I need to measure the
    bounds of the text (which is going to be surrounded by the rectangle).
    The DebugGraphics looks nice but it has two problems :
    1. Heavy to instantiate. Is there any lightweight alternative.
    2. Doesn't handle the Line formatting.
    It is possible to do simple text formatting (by \t and \n) using simple
    regular expressions and then getting the bounds using DebugGraphics.
    But, is there any other more interesting solution available ?
    Cheers,
    Ali Salehi

  • A short and fundamental question: Java3D in headless mode

    To begin I would like to introduce myself as a complete Java3D newbie.
    What I would like to accomplish is to produce an application which, in headless mode, will read in data and generate 3d images as files, without ever making any GUI components to appear on the screen.
    Is this possible?
    Thanks!

    When you say "unix doesn't have Arial" you obviously aren't using Solaris where Arial most certainly
    ships and is in fact the main font used to support dialog & sanserif.
    There are numerous APIs to calculate the width of a string in pixels, depending on whether
    you want the integer metrics, fp metrics , logical bounds, pixel bounds (which guarantees to enclose
    every pixel if you correctly specify the graphics/FRC)
    Every single one of these works in headless mode.
    Even the most simple-minded FontMetrics.stringWidth(String) call should be good enough
    for your requirements.
    The error you show looks like you have a misconfigured environment.. It can't find
    the correct implementation class of GraphicsEnvironment which is nothing to do with
    fonts. Moreover this DOES work for me :
    import java.awt.*;
    public class Arial {
    public static void main(String args[]) {
    Font arial = new Font("Arial", Font.PLAIN, 10);
    System.out.println(arial);
    % java -version
    java version "1.4.2_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_01-b06)
    Java HotSpot(TM) Client VM (build 1.4.2_01-b06, mixed mode)
    % java -Djava.awt.headless=true Arial
    java.awt.Font[family=Arial,name=Arial,style=plain,size=10]
    QED.
    -Phil.

Maybe you are looking for

  • How to find hidden message in photo

    I have been given a photo as part of a puzzle. There is a message hidden in the photo. It is most probably GPS coordinates. Is there a way to find the message using photoshop? The image is a .gif. I would be grateful for some help. Miss_Kissen

  • Non-heap memory area spring leak  in JVM 1.50_6

    Please let me question though it doesn't understand be good from this topic. A problem occurs when testing as follows. The problem is to generate memory leak in non-heap area. %java CconnectTest2 129.24.34.68 130.104.10.50 6101 5000 185000 100 (%java

  • Why use only 3gb ram when instaled 4 gb?

    why use only 3gb ram when instaled 4 gb?? macbook 2,1 late 2007 mac os 10.6.8 Название модели:    MacBook       MacBook2,1       Intel Core 2 Duo    2.16 ГГц RAM:   4 ГБ  667 МГц   Версия Boot ROM:    MB21.00A5.B07   Версия SMC (система):    1.17f0  

  • Authorisation of computer

    I bought a new computer and transferred everything across. When I tried to download podcast on to iphone 3gs it said it was not authorised. I authorised it but each time I try to download it says I am not but when I go to authorise it says it is alre

  • Change in Position Type In Sales Order.

    Hi All,        My Customer has a Requirement at the Time of Creation and change of Sales Order if the Position Type of Item is ZTA1 and User Status is 'INDL' position type has to be changed to ZTA2.        I tried that with all Exits in MV45AFZZ the