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.

Similar Messages

  • 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

  • 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.

  • Determining the actual length of a string based on pixels?

    How would you determine the actual length of a string based on pixels? Reason for is because a length of a string containing all " l " chars would be a lot smaller then the length of a string containing all "H" chars based on pixel width.
    thanks,
    newbie

    Yes, look at the FontMetrics class which has methods to do just that. To get a relevant FontMetrics object, try "x.getFontMetrics(f)" where x is a Component and f is the Font your string is represented in.

  • 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

  • Length of a string (text) in pixels.

    I'm trying to locate a String's center on an exact position, drawing it to a JPanel. But since i don't know the exact length of the string, it's not that easy. Can anybody help me out there?

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class CenteringStrings
        public static void main(String[] args)
            StringDemoPanel demo = new StringDemoPanel();
            DemoActionPanel action = new DemoActionPanel(demo);
            JFrame f = new JFrame("Centering Strings");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(action, "East");
            f.getContentPane().add(demo);
            f.setSize(500,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class StringDemoPanel extends JPanel
        String text;
        Font font;
        final int
            ASCENT   = 0,
            DESCENT  = 1,
            LEADING  = 2,
            BASELINE = 3;
        int index = -1;
        boolean sizeFlag, boundsFlag;
        public StringDemoPanel()
            text = "Centered text";
            font = new Font("lucida sans oblique", Font.PLAIN, 36);
            sizeFlag = false;
            boundsFlag = false;
            setBackground(Color.white);
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setFont(font);
            FontRenderContext frc = g2.getFontRenderContext();
            LineMetrics lm = font.getLineMetrics(text, frc);
            TextLayout tl = new TextLayout(text, font, frc);
            int w = getWidth();
            int h = getHeight();
            float textWidth = (float)font.getStringBounds(text, frc).getWidth();
            float ascent  = lm.getAscent();
            float descent = lm.getDescent();
            float leading = lm.getLeading();
            float height  = lm.getHeight();
            float x = (w - textWidth)/2;
            float y = (h + height)/2 - descent;
            g2.drawString(text, x, y);
            // marker for string origin (x,y) on baseline
            //g2.setPaint(Color.blue);
            //g2.fill(new Ellipse2D.Double(x - 1, y - 1, 2, 2));
            // physical space of text
            Rectangle2D textSize = tl.getBounds();
            textSize.setFrame(x, y - textSize.getHeight(),
                              textSize.getWidth(), textSize.getHeight());
            // string bounds
            Rectangle2D bounds = font.getStringBounds(text, frc);
            bounds.setFrame(x, y - ascent - leading, bounds.getWidth(), bounds.getHeight());
            switch(index)
                case ASCENT:
                    Rectangle2D r1 = new Rectangle2D.Double(x, y - ascent, textWidth, ascent);
                    g2.setPaint(Color.magenta);
                    g2.draw(r1);
                    break;
                case DESCENT:
                    Rectangle2D r2 = new Rectangle2D.Double(x , y, textWidth, descent);
                    g2.setPaint(Color.orange);
                    g2.draw(r2);
                    break;
                case LEADING:
                    Rectangle2D r3 = new Rectangle2D.Double(x, y - ascent - leading,
                                                            textWidth, leading);
                    g2.setPaint(Color.yellow);
                    g2.draw(r3);
                    break;
                case BASELINE:
                    Line2D line = new Line2D.Double(x, y, x + textWidth, y);
                    g2.setPaint(Color.blue);
                    g2.draw(line);
            if(sizeFlag)
                g2.setPaint(Color.green);
                g2.draw(textSize);
                System.out.println("above size = " + (int)textSize.getY() + "\n" +
                                   "below size = " +
                                   (int)(h - (textSize.getY() + textSize.getHeight())));
            if(boundsFlag)
                g2.setPaint(Color.red);
                g2.draw(bounds);
                System.out.println("above bounds = " + (int)bounds.getY() + "\n" +
                                   "below bounds = " +
                                   (int)(h - (bounds.getY() + bounds.getHeight())));
        public void setIndex(int i)
            index = i;
            repaint();
        public void setSizeFlag(boolean flag)
            sizeFlag = flag;
            repaint();
        public void setBoundsFlag(boolean flag)
            boundsFlag = flag;
            repaint();
    class DemoActionPanel extends JPanel
        StringDemoPanel sdp;
        JRadioButton
            ascentButton, descentButton, leadingButton, baselineButton, clearButton;
        JRadioButton[] buttons;
        JCheckBox
            sizeCheck, boundsCheck;
        JCheckBox[] checks;
        public DemoActionPanel(StringDemoPanel p)
            sdp = p;
            createComponents();
        private void createComponents()
            ascentButton   = new JRadioButton("ascent");
            descentButton  = new JRadioButton("descent");
            leadingButton  = new JRadioButton("leading");
            baselineButton = new JRadioButton("baseline");
            clearButton    = new JRadioButton("clear");
            buttons = new JRadioButton[] {
                ascentButton, descentButton, leadingButton, baselineButton, clearButton
            ButtonGroup group = new ButtonGroup();
            RadioButtonListener buttonListener = new RadioButtonListener();
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weighty = 1.0;
            gbc.insets = new Insets(2,2,2,2);
            gbc.gridwidth = gbc.REMAINDER;
            gbc.anchor = gbc.WEST;
            for(int i = 0; i < buttons.length; i++)
                add(buttons, gbc);
    group.add(buttons[i]);
    buttons[i].addActionListener(buttonListener);
    sizeCheck = new JCheckBox("text size");
    boundsCheck = new JCheckBox("bounds");
    checks = new JCheckBox[] { sizeCheck, boundsCheck };
    CheckBoxListener checkBoxListener = new CheckBoxListener();
    for(int i = 0; i < checks.length; i++)
    add(checks[i], gbc);
    checks[i].addActionListener(checkBoxListener);
    private class RadioButtonListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    JRadioButton button = (JRadioButton)e.getSource();
    if(button == clearButton)
    sdp.setIndex(-1);
    return;
    for(int i = 0; i < buttons.length; i++)
    if(button == buttons[i])
    sdp.setIndex(i);
    break;
    private class CheckBoxListener implements ActionListener
    public void actionPerformed(ActionEvent e)
    JCheckBox checkBox = (JCheckBox)e.getSource();
    if(checkBox == sizeCheck)
    sdp.setSizeFlag(sizeCheck.isSelected());
    if(checkBox == boundsCheck)
    sdp.setBoundsFlag(boundsCheck.isSelected());

  • How is the length of a string calculated in Java?  and JavaScript?

    Hi all,
    Do any of you know how the length of a string is being calculated in Java and JavaScript? For example, a regular char is just counted as 1 char, but sometimes other chars such as CR, LF, and CR LF are counted as two. I know there are differences in the way Java and JavaScript calculate the length of a string, but I can't find any sort of "rules" on those anywhere online.
    Thanks,
    Yim

    What's Unicode 4 got to do with it? 1 characteris 1
    character is 1 character.
    strings now contain (and Java chars also) is
    UTF-16 code units rather than Unicode characters
    or
    code points. Unicode characters outside the BMPare
    encoded in Java as two or more code units. So it would seem that in some cases, a single
    "character" on the screen, will require two charsto
    represent it.So... you're saying that String.length() doesn't
    account for that? That sux. I don't know. I'm just making infrerences (==WAGs) based on what DrClap said.
    I assume it would return the number of chars in the array, rather than the number of symbols (glyphs?) this translates into. But I might have it bass ackwards.

  • Length of a string in a combobox exceeds the width of the combobox

    How do you fix this:
    The length of a string in a combobox exceeds the width of the combobox and as a result, the comboBox changes its size :-(
    I don't want it to change the size even if the length of the string exceeds the width of the comboBox
    what should i do?

    ok i got it
              Dimension d =combo.getPreferredSize();
    combo.setPreferredSize(new Dimension(50, d.height));
    anyone with better solution?

  • How to find the total length of the string drawed in a rect?

    Hello Everybody,
    I am drawing a string in on one rect using drawInRect method. This drawInRect method gives us a return value as size of the rect. I need length of the string that is did draw in that rect, but didn't find any api to do this.
    Can anyone tell me , how find the length of the string which we did draw in rect?
    Any help regarding this issue , is highly appreciable.
    Thanks,
    Pandit

    Hi Adreas,
    First of all, very thanks for the response.
    Actually , I am looking for other thing. Using drawInRect method I am drawing contentString in self.rect like below.
    //code
    [contentString drawInRect:self.rect withFont:[UIFont fontWithName:@"Verdana" size:14.0] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
    //End
    My contentString is much larger string, so I am not able to draw it in rect(length: 320.0 height: 460.0) completely. My rect is showing only a part of a contentString. So I need to get that part of string which did draw in the rect, so that I can process my contentString to get the remaining string to draw it a next rect.
    The above code statement is returning me the CGSIZE , it is giving the size of the rect but not giving any information of the string which get draw in that rect.Do you have any idea how to do this?
    Any information on this is highly appreciable.
    Thanks,
    Pandit

  • Length of a string without using any built-in functions

    code that returns the length of a string without using any built-in functions.
    thanks
    Sam

    A string is internally represented by a character array.  An array of characters will reside on the stack, not the heap.  Yes, we always learned that String is a reference type, but what goes on in your memory might still surprise you...
    A struct is internally represented by only it's private properties, sequentially on the stack.
    So basically, what I thought is happening by messing with the structlayout: is only tricking our programming a bit into thinking that the top X bytes on the stack represent a chararray, while actually we put them there as a string.
    Wrong. True. And wrong.
    A string is internally represented by, in that order, an array length, a string length, the chars. None of them resides on the stack.
    An array is internally represented by, in that order, an array length and the chars. None of them resides on the stack.
    When you use the FieldOffset attribute to handle the string as a char array, you don't get anything right:
    - the Length returned is the "array length" of the string, which is equal to the string length + 1.
    - the chars returned by the array indexer are shifted by 2 chars (the length of the "string length" field).
    You can use the FieldOffset to make that work, but it needs a little bit more work.
    unsafe static int Test()
    string myString = "This string may contain many string inside this string";
    string testString = "string";
    int countResult = 0;
    fixed (char* myChars = new StringToChar { str = myString }.chr, testChar = new StringToChar { str = testString }.chr)
    // The 2 first chars of the array are actually the string length.
    int myCharsLength = myChars[1] << 16 | myChars[0];
    int testCharLength = testChar[1] << 16 | testChar[0];
    for (int i = 0; i < myCharsLength - testCharLength + 1; i++)
    if (myChars[i + 2] == testChar[2])
    for (int j = 1; j < testCharLength; j++)
    var c = testChar[7];
    if (myChars[i + 2 + j] != testChar[j + 2])
    goto endOfCharAnalyses;
    countResult++;
    endOfCharAnalyses:
    continue;
    return countResult;

  • Length of the string passed to rwcgi60 in Oracle 6i

    Hello,
    I am running the report from the web. The url will be something like
    http://localhost/cgi-bin/rwcgi60.exe?server=repserver+report=.rep+all the input parameters.
    When the length of the string passed from report= execeeds certain limit(indicated by dashes) I am getting the cgi error
    Error: The requested URL was not found, or cannot be served at this time.
    Oracle Reports Server CGI - Unable to communicate with the Reports Server.
    If I remove some of the select criteria then I could execute the report from the web.
    Any body has any soln. for this.
    Thanks in advance,
    Vanishri.

    Vanishri
    The limit is very high and you should not be hitting this problem. There are couple of fixes done in this area. Please apply the latest patch (Patch 10) and try.
    Other solution is you can have a mapped key in cgicmd.dat file and use the key alone in the URL. In the cgicmd.dat file, you have to map say
    key1: REPORT=your_report.rdf USERID=user_name/password@mydb DESFORMAT=html
    SERVER=repserver DESTYPE=cache
    Please refer to the Publishing reports or Reports services manual at http://otn.oracle.com/docs/products/reports/content.html
    Thanks
    The Reports Team

  • PowerShell: Want to get the length of the string in output

    Hi All,
    I am typing this but it is not working. Does anyone know what I could be doing wrong.
    The command I wrote is:
                         GCI -file  | foreach {$_.name} | sort-object length | format-table name, length
    But it is not working. I am expecting a name of the file and length of the string like 8 characters etc. my file is called mystery so it should have 7 as its output of the name, length.
    Thank-you
    SQL 75

    Get-ChildItem supports both  -File and -Directory.
    Help will help:
    https://technet.microsoft.com/library/hh847897(v=wps.630).aspx
    Read the first couple of parameters to see.
       GCI -file  | sort-object length | format-table name, length | ft -auto
    Seems to be a rasher of bad answers to day.  YOu were just extracting the name property then trying to sort on a property that doesn't exist.
    Do the sort first then select the properties.
    it helps to test answers before posting.  I know because I get bit by posting without thinking to often.  I have to remember to think first.
    ¯\_(ツ)_/¯

  • Variable length declaration in string type

    hi all
    can anyone tell me how to declare length for string type of variables

    Hi,
    The length of a string is not static but variable and adjusts itself to the current field content at runtime. Dynamic memory management is used internally. Strings can have any length. The initial value of a string is an empty string with length 0.
    Hope this will make you clear. Please reward if answer satisfy you !!!
    Regards,
    Jignesh

  • How to calculate the length of a string

    Hi everyone,
    A simple question. How to calculate the length of a string?
    Thanks!

    Hi Wuyia Nata,
      As everyone has suggested you search the forum before posting a question, i guess for basic questions u never have to post a question, you will get the answer in your search. Anyways see the code below for string lenght.
    Data:
      w_string type string,
      w_lenght type i.
    w_string = 'vhdskbvsdkbvdsvnsknvs'.
    w_lenght = strlen( w_string ).
    Write:
      w_lenght.
    With luck,
    Pritam.

  • Want to length of the string

    Hi,
    I have one parameter on the selection screen, when i enter some string on that, it should give me the length of the string. can you pls send me the code.
    Ex: if i enter : enter amount : then it should give the o/p is: 12
    Akshitha.

    use FM
    SWA_STRINGLENGTH_GET  
    enter your string in EXPRESSION and use the others if needed use "X" for all three except EXPRESSION
    EXPRESSION                      GFFHG      
    <b>CONDENSE_NO_GAPS                           
    CONDENSE                                   
    WITH_LEADING_BLANKS                        </b>
    also see STRING_LENGTH
        STRING_LENGTH
    Message was edited by:
            Amit Singla

Maybe you are looking for

  • One customer entry is not comming into datasource.

    Hi, I did not get one of customer Line item details in Datasource. But i can see the data  in FB03. what will be the reason. Regards.

  • Best way to create nice, wide vocals from a 2 part harmony?

    I know there's no "best" way. But I have a chorus line I've written with a two part harmony. I want it to sound wide and full. What's a good approach to take right now. How many passes of each vocal line should I record? What approach should I take w

  • Simulate Download not working

    I want to check to make sure my preloader is working right, so I'm trying to use the Simulate Download function.  At any speed, when I start the simulation, it just sits there, and does nothing.  No images, no backgound, nothing.  Running the program

  • ITunes store error code -9813....

    unable to create a new account or log into existing accounts ONLY from my Mac.....no issues from my windows based laptop. both on on the same home network. issued has occurred for over a month.

  • OCCI with gcc 3.2

    Has anybody had luck with OCCI with gcc 3.2? I am having problems linking the libraries and it seems that OCCI does not support gcc3.2. Does anyone know what version of gcc is supported for Oracle 9.2 ,as I couldn't find any information about support