How do I get a strings width w/o getFontMetrics()?

Now that getFontMetrics() is deprecated - how am I supposed to get the width of a string? The FontMetrics class had a stringWidth() method.

I dont have the API docs here so I cant give u the exact method names and classes but heres generally how you can do it: You have the Graphics object for the screen/whatever that you want to calculate the bounds for so do this
Graphics2D g = ...
FontRenderContext frc = g.getFontRenderContext();
Font font = g.getFont();
Rectangle2D bounds = font.getStringBounds("foo", frc);
or something like that, and if you dont have the Graphics object you can always pass that part by calling the FontRenderContext constructor and passing some null values to it and so creating your own context that does some basic calculations correctly anyways.. Enuff for any font bounds anyway.

Similar Messages

  • How can I get the image width and height stored in database?

    Hi!I write s servlet to display images store in database.but how can I get the image width and height?

    Have you tryed using PJA or a similar library?
    I presume you get java.lang.NoClassDefFoundError on the line :
    Toolkit.getDefaultToolkit();?

  • How do i get the max width and height?

    Hey
    I want to get the max width and height, so my desktoppanes size can be set automatically.
    I know i should use getBounds but i cant find a concrete example on goole, on how to use it.
    Can someone point me in the right direction, with an example?

    Ok, assuming you want to get the screen resolution, i.e. 1024 x 768.
    You will need these imports:
    import java.awt.Dimension;
    import java.awt.Toolkit;and this line of code:
    Dimension myScreen =  Toolkit.getDefaultToolkit().getScreenSize() ;You can now use myScreen.width and myScreen.height to access the height and width of your screen's resolution. (width = 1024, height = 768 in my case)
    Hope this helps,
    Stern
    Edited by: Stern on Apr 13, 2008 6:49 AM

  • How do i get a String out of an ArrayList?

    I was trying to make a list I could grow and I was informed that arrays couldn't grow, an ArrayList was suggested.
    This seems like it will work perfectly except for the fact that I can't retrieve a String from the ArrayList.
    I'm getting errors like incompatible type String:Object or expected:[] found ArrayList.
    I tried .toString but that just gives me a bunch of giberish.
    Any advice would be most welcome.
    Thanks in advance,
    Hans.

    Ok, so, i guess here is some code you can run, it should run.
    I guess I want to know how to get each individual string out of the list one at a time.
    package arraylistone;
    import javax.swing.JFrame;
    import java.util.ArrayList;
    import javax.swing.JLabel;
    public class Main extends JFrame
                JLabel label = new JLabel();
                ArrayList list = new ArrayList();
        public Main()
            String str = "test";
            String str2 = "test2";
            list.add(str);
            list.add(str2);
            label.setText("Not Working");
            label.setText(list.toArray().toString());
                    getContentPane().add( label);
        public static void main(String[] args)
            Main frame = new Main();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • How could java get two strings from c function?

    As title! I want to let a java code call C function. And the C funtion returns two unsigned char pointers.
    Thanks a lot.

    I have the other problem. When compile the code with jnienv, it always shows errors...It's because the code I posted is for C compiler, not C++.
    Here is a complete example in C++.
    Just compile the Java part, then the C++ part, then run it at the console:
    java TestCStringIt should give you:
    Hello
    World!
    // TestCString.java
    class TestCString
        static
            System.loadLibrary("testcstring");
        native String[] getStrings();
        public static void main(String[] args)
            TestCString test = new TestCString();
            String[] strArray = test.getStrings();
            System.out.println(strArray[0]);
            System.out.println(strArray[1]);
    // testcstring.h
    #ifndef _Included_TestCString
    #define _Included_TestCString
    #include <jni.h>
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class:     TestCString
    * Method:    getStrings
    * Signature: ()[Ljava/lang/String;
    JNIEXPORT jobjectArray JNICALL Java_TestCString_getStrings(JNIEnv * env, jobject obj);
    #ifdef __cplusplus
    #endif
    #endif /* _Included_TestCString */
    // testcstring.cpp
    #include "testcstring.h"
    static char * g1 = "Hello";
    static char * g2 = "World!";
    static void myCFunc(unsigned char ** pp1, unsigned char ** pp2)
        *pp1 = (unsigned char *)g1;
        *pp2 = (unsigned char *)g2;
    * Class:     TestCString
    * Method:    getStrings
    * Signature: ()[Ljava/lang/String;
    JNIEXPORT jobjectArray JNICALL Java_TestCString_getStrings(JNIEnv * env, jobject obj)
        unsigned char * p1;
        unsigned char * p2;
        jstring str1;
        jstring str2;
        jclass strCls;
        jobjectArray strArray;
        myCFunc(&p1, &p2); // call the c function
        str1 = env->NewStringUTF((const char *)p1); // create java string with first pointer
        str2 = env->NewStringUTF((const char *)p2); // create java string with second pointer
        strCls = env->FindClass("java/lang/String");
        strArray = env->NewObjectArray(2, strCls, NULL); // create java string array
        env->SetObjectArrayElement(strArray, 0, str1); // set first element
        env->SetObjectArrayElement(strArray, 1, str2); // set second element
        return strArray; // return java string array
    }Regards

  • How can I get a list of the names of the failed steps ?

    Hi,
       I wanted to have a string which can describe all the failed steps. For example, if I had the steps below :
    Step 1
    Step 2
    Step 3, etc
    and Step 1 and Step 3 failed, how can I get a string " Step1, Step2" ?
    Can I somehow add a variable in each step which records the step result and then use all the variables at the end to creat a Result string ?
    Please help.
    ~Sam~

    Sam,
    you have at least two possibilities for your question:
    a) use the "SequencePostResultListEntry"-callback. You can check the "Step.Result.Status". If it is failed, you can copy the stepname into a string-variable which builds your "string"
    b) In the end of your MainSequence, just browse your ResultList for every step which has Result.Status as failed. Copy all stepnames into your string.
    Both methods require your station to record results, but since this is defaultsetting, there shouldn't be a problem.
    hope this helps,
    Norbert B.
    CEO: What exactly is stopping us from doing this?
    Expert: Geometry
    Marketing Manager: Just ignore it.

  • Get the stage.width before including on DisplayList

    Hi!
    I have a component, that automatically get the stage.width
    and stage.height. But the property stage is not valid until I draw
    the component with a addChild method. I would like to get the
    stage.width and stage.height properties without needing to include
    the component on the DisplayList.
    So, two questions:
    1. Is there a way to get the stage.width and stage.height
    without adding it to DisplayList (with a addChild)?
    2. What is my component does not extens a DisplayObject, how
    do I get the stage.width?
    Thank you,
    CaioToOn!

    So, any suggestions?
    CaioToOn!

  • How can i get also the files in the root directory and how can i for testing add items of IEnumerable FTPListDetail to List string ?

    What i get is only the directories and files that in other nodes. But i have also files on the root directory and i never
    get them. This is a screenshot of my program after i got the content of my ftp. I'm using treeView to display my ftp content:
    You can see two directories from the root but no files on the root it self. And in my ftp server host i have files in the root direcory.
    This is the method i'm using to get the directory listing:
    public IEnumerable<FTPListDetail> GetDirectoryListing(string rootUri)
    var CurrentRemoteDirectory = rootUri;
    var result = new StringBuilder();
    var request = GetWebRequest(WebRequestMethods.Ftp.ListDirectoryDetails, CurrentRemoteDirectory);
    using (var response = request.GetResponse())
    using (var reader = new StreamReader(response.GetResponseStream()))
    string line = reader.ReadLine();
    while (line != null)
    result.Append(line);
    result.Append("\n");
    line = reader.ReadLine();
    if (string.IsNullOrEmpty(result.ToString()))
    return new List<FTPListDetail>();
    result.Remove(result.ToString().LastIndexOf("\n"), 1);
    var results = result.ToString().Split('\n');
    string regex =
    @"^" + //# Start of line
    @"(?<dir>[\-ld])" + //# File size
    @"(?<permission>[\-rwx]{9})" + //# Whitespace \n
    @"\s+" + //# Whitespace \n
    @"(?<filecode>\d+)" +
    @"\s+" + //# Whitespace \n
    @"(?<owner>\w+)" +
    @"\s+" + //# Whitespace \n
    @"(?<group>\w+)" +
    @"\s+" + //# Whitespace \n
    @"(?<size>\d+)" +
    @"\s+" + //# Whitespace \n
    @"(?<month>\w{3})" + //# Month (3 letters) \n
    @"\s+" + //# Whitespace \n
    @"(?<day>\d{1,2})" + //# Day (1 or 2 digits) \n
    @"\s+" + //# Whitespace \n
    @"(?<timeyear>[\d:]{4,5})" + //# Time or year \n
    @"\s+" + //# Whitespace \n
    @"(?<filename>(.*))" + //# Filename \n
    @"$"; //# End of line
    var myresult = new List<FTPListDetail>();
    foreach (var parsed in results)
    var split = new Regex(regex)
    .Match(parsed);
    var dir = split.Groups["dir"].ToString();
    var permission = split.Groups["permission"].ToString();
    var filecode = split.Groups["filecode"].ToString();
    var owner = split.Groups["owner"].ToString();
    var group = split.Groups["group"].ToString();
    var filename = split.Groups["filename"].ToString();
    var size = split.Groups["size"].Length;
    myresult.Add(new FTPListDetail()
    Dir = dir,
    Filecode = filecode,
    Group = group,
    FullPath = CurrentRemoteDirectory + "/" + filename,
    Name = filename,
    Owner = owner,
    Permission = permission,
    return myresult;
    And then this method to loop over and listing :
    private int total_dirs;
    private int searched_until_now_dirs;
    private int max_percentage;
    private TreeNode directories_real_time;
    private string SummaryText;
    private TreeNode CreateDirectoryNode(string path, string name , int recursive_levl )
    var directoryNode = new TreeNode(name);
    var directoryListing = GetDirectoryListing(path);
    var directories = directoryListing.Where(d => d.IsDirectory);
    var files = directoryListing.Where(d => !d.IsDirectory);
    total_dirs += directories.Count<FTPListDetail>();
    searched_until_now_dirs++;
    int percentage = 0;
    foreach (var dir in directories)
    directoryNode.Nodes.Add(CreateDirectoryNode(dir.FullPath, dir.Name, recursive_levl+1));
    if (recursive_levl == 1)
    TreeNode temp_tn = (TreeNode)directoryNode.Clone();
    this.BeginInvoke(new MethodInvoker( delegate
    UpdateList(temp_tn);
    percentage = (searched_until_now_dirs * 100) / total_dirs;
    if (percentage > max_percentage)
    SummaryText = String.Format("Searched dirs {0} / Total dirs {1}", searched_until_now_dirs, total_dirs);
    max_percentage = percentage;
    backgroundWorker1.ReportProgress(percentage, SummaryText);
    percentage = (searched_until_now_dirs * 100) / total_dirs;
    if (percentage > max_percentage)
    SummaryText = String.Format("Searched dirs {0} / Total dirs {1}", searched_until_now_dirs, total_dirs);
    max_percentage = percentage;
    backgroundWorker1.ReportProgress(percentage, SummaryText);
    foreach (var file in files)
    TreeNode file_tree_node = new TreeNode(file.Name);
    file_tree_node.Tag = "file" ;
    directoryNode.Nodes.Add(file_tree_node);
    numberOfFiles.Add(file.FullPath);
    return directoryNode;
    Then updating the treeView:
    DateTime last_update;
    private void UpdateList(TreeNode tn_rt)
    TimeSpan ts = DateTime.Now - last_update;
    if (ts.TotalMilliseconds > 200)
    last_update = DateTime.Now;
    treeViewMS1.BeginUpdate();
    treeViewMS1.Nodes.Clear();
    treeViewMS1.Nodes.Add(tn_rt);
    ExpandToLevel(treeViewMS1.Nodes, 1);
    treeViewMS1.EndUpdate();
    And inside a backgroundworker do work how i'm using it:
    var root = Convert.ToString(e.Argument);
    var dirNode = CreateDirectoryNode(root, "root", 1);
    e.Result = dirNode;
    And last the FTPListDetail class:
    public class FTPListDetail
    public bool IsDirectory
    get
    return !string.IsNullOrWhiteSpace(Dir) && Dir.ToLower().Equals("d");
    internal string Dir { get; set; }
    public string Permission { get; set; }
    public string Filecode { get; set; }
    public string Owner { get; set; }
    public string Group { get; set; }
    public string Name { get; set; }
    public string FullPath { get; set; }
    Now the main problem is that when i list the files and directories and display them in the treeView it dosen't get/display
    the files in the root directory. Only in the sub nodes.
    I will see the files inside hello and stats but i need also to see the files in the root directory.
    1. How can i get and list/display the files of the root directory ?
    2. For the test i tried to add to a List<string> the items in var files to see if i get the root files at all.
       This is what i tried in the CreateDirectoryNode before it i added:
    private List<string> testfiles = new List<string>();
    Then after var files i did:
    testfiles.Add(files.ToList()
    But this is wrong. I just wanted to see in testfiles what items i'm getting in var files in the end of the process.
    Both var files and directoryListing are IEnumerable<FTPListDetail> type.
    The most important is to make the number 1 i mentioned and then to do number 2.

    Risa no.
    What i mean is this. This is a screenshot of my ftp server at my host(ipage.com).
    Now this is a screenshot of my program and you can see that in my program i have only the directories hello stats test but i don't have the files in the root: htaccess.config swp txt 1.txt 2.png....all this files i don't have it on my treeView.
    What i want it to be is that on my program on the treeView i will also display the files like in my ftp server.
    I see in my program only the directories and the files in the directories but i don't see the files on the root directory/node.
    I need it to be like in my ftp server i need to see in my program the htaccess 1.txt 2.png and so on.
    So what i wrote in my main question is that in the var files i see this files of the root directory i just don't know to add and display them in my treeView(my treeView is treeViewMS1).
    I know i checked in my program in the method CreateDirectoryNode i see in the first iteration of the recursive that var files contain this root files i just dont know how to add and display them in my treeView.
    On the next iterations when it does the recursive it's adding the directories hello stats test and the files in this directories but i need it to first add the root files.

  • How can i get the length of a string with Simplified Chinese?

    when i use eventwriter to add content to a xmldocument,there are some chinese simplified string in it,i use String.length() for the length ,but it is not correct~how can i get the right length for eventwriter?

    Below is a simple patch for this problem. Using this patch you need to pass 0 as the length argument for any XmlEventWriter interfaces that take a string length.
    Regards,
    George
    diff -c dbxml-2.3.10/dbxml/src/dbxml/nodeStore/NsEventWriter.cpp dbxml-2.3.10.patch/dbxml/src/dbxml/nodeStore/NsEventWriter.cpp
    *** dbxml-2.3.10/dbxml/src/dbxml/nodeStore/NsEventWriter.cpp    Fri Nov  3 12:26:11 2006
    --- dbxml-2.3.10.patch/dbxml/src/dbxml/nodeStore/NsEventWriter.cpp      Thu Mar 15 13:58:13 2007
    *** 234,239 ****
    --- 234,241 ----
            CHECK_NULL(text);
            CHECK_SUCCESS();
    +       if (!length)
    +               length = ::strlen((const char *)text);
            if (!_current)
                    throwBadWrite("writeText: requires writeStartDocument");
            try {
    *** 413,418 ****
    --- 415,422 ----
            CHECK_NULL(dtd);
            CHECK_SUCCESS();
    +       if (!length)
    +               length = ::strlen((const char *)dtd);
            if (_current) {
                    if (!_current->isDoc())
                            throwBadWrite("writeDTD: must occur before content");
    diff -c dbxml-2.3.10/dbxml/src/dbxml/nodeStore/NsWriter.cpp dbxml-2.3.10.patch/dbxml/src/dbxml/nodeStore/NsWriter.cpp
    *** dbxml-2.3.10/dbxml/src/dbxml/nodeStore/NsWriter.cpp Tue Jan  2 16:01:14 2007
    --- dbxml-2.3.10.patch/dbxml/src/dbxml/nodeStore/NsWriter.cpp   Thu Mar 15 13:59:25 2007
    *** 326,331 ****
    --- 326,333 ----
                    needsEscape = false;
            else
                    needsEscape = true;
    +       if (!length)
    +               length = ::strlen((const char *)chars);
            writeTextWithEscape(type, chars, length, needsEscape);
    *** 336,341 ****
    --- 338,345 ----
                                  bool needsEscape)
            if(_entCount == 0) {
    +               if (!len)
    +                       len = ::strlen((const char *)chars);
                    if ((type == XmlEventReader::Characters) ||
                        (type == XmlEventReader::Whitespace)) {
                            char *buf = 0;
    *** 381,386 ****
    --- 385,392 ----
      NsWriter::writeDTD(const unsigned char *data, int len)
            if(_entCount == 0) {
    +               if (!len)
    +                       len = ::strlen((const char *)data);
                    _stream->write(data, len);
      }

  • How can I get the ID number of an attribute, based on the name string?

    In an IVI driver, how can I get the list of attributes of an instrument? Is there a way to retrieve the long type representation of an attribute ID, based on the string name? Say, I put "IVIDMM_ATTR_FUNCTION", and I receive the long number (i.e. 1150010), so I can call the SetAttribute function?
    Thanks.

    Hello-
    Tokens like IVIDMM_ATTR_FUNCTION are actually macros that have been #define'd in a header file. Many of the headers are found in C:\VXIPNP\WIN95\include. For example, the macro for IVIDMM_ATTR_FUNCTION is found on line 111 of ividmm.h.
    Randy Solomonson
    Application Engineer
    National Instruments

  • No width/height set for items.This will cause an infinite loop. Aborting....... How do I get out of this?

    How do I get out of this?

    What are you talking about? The width/height of what? Is this some sort of error message? If so from what?

  • How do I get rid of this annoying tag at the end of my wordpress posts: // ![CDATA[ div id="" class="_mp3rocket_overlay_style" style="left: ; top: ; width: ;

    Whenever I post on my blog, this shows up at the bottom:
    <pre><nowiki>// <![CDATA[
    <div id="" class="_mp3rocket_overlay_style" style="left: ; top: ; width: ; height: ">
    // ]]>
    </nowiki></pre>
    How do I get rid of it?

    Does the name mp3rocket ring a bell?? It may be related to a browser add-on. You could check for and possibly disable or remove such an add-on here:
    orange Firefox button ''or'' classic Tools menu > Add-ons
    Try both the Plugins and Extensions categories.
    If it doesn't seem related to an add-on, perhaps it's something added by a Wordpress plugin, or your blog theme. If you provide a link to your blog, a volunteer here could take a look and see whether they get the same text.

  • How to get a string "yyyyMMdd" into date like MM/dd/yyyy?.

    Hi
    How to get a string "yyyyMMdd" into date like MM/dd/yyyy?. i have used
    SimpleDateFormat.parse but it is giving long value. i want to disply the date
    like MM/dd/yyyy
    thank you

    Do you want the string rearranged or do you want to create an instance of some form of Date class?
    If you want to rearrange the string you could just do it yourself provided you know the date string is going to be of the format yyyyMMdd.
    something like this:
    String newDate = origStr.charAt(4) + origStr.charAt(5) + "/" + origStr.charAt(6) + origStr.charAt(7) + "/" ...etc.

  • [CS2]How to get the Image Width & Height using JS (ILLUSTRATOR CS2)

    Hi,
    How to get the Image width & height of an Image using javascript .Im using Illustrator CS2.
    Any sample code
    Regards
    MyRiaz

    you can reference the dimensions of a loading image (or swf)
    by referencing the target movieclip's dimensions AFTER loading is
    complete. ie, use preloader code or the onLoadInit() method of a
    moviecliploader listener.

  • How can i get getwayed url string using pluggable nav in news portlet?

    hi.
    How can i get getwayed url string using pluggable nav in news portlet?
    A code just like below is what I want.
    <param value="param=http://.../portal/server.pt/gateway/PTARGS_.../http/...">
    I tryed the following, but didn't work as I wanted.
    1.<param value="<pcs:valueexpr='var'/>">
    -> transformed. but I want the prefix 'param=' in the enquoted string's too.
    2. <param value="param=<pcs:valueexpr='var'/>">
    -> not transformed.
    Any idea?
    Hiroyuki

    Hi all,
    We have HPROF functionality in our latest roadmap, so you will see that feature in our next major release called JRockit R28.
    I recommend, above from the MemLeak documentation suggested by Makiey, the following information on how to use JRockit tools.
    Performance Tuning & Profiling:
    http://download.oracle.com/docs/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/part_02.html
    Using JRockit tools:
    http://download.oracle.com/docs/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/part_03.html
    Diagnostics & Troubleshooting
    http://download.oracle.com/docs/cd/E13150_01/jrockit_jvm/jrockit/geninfo/diagnos/part_04.html
    Best Regards,
    Tuva
    JRockit PM

Maybe you are looking for