How get area covered by text drawn on a jpanel?

I'm trying to get the full area that a string of text covers when drawn on a JPanel. I use the below code and the width seems to be correct, but the height is wrong (I use it to make the mouse cursor change when over it). I can't seem to get the exact location of every pixel of the characters. It's either too low or misses the bottom part (I've been altering the code a lot). What am I doing wrong?
//Widest line
int widest = 0;
int totalHeight = 0;
//Loop through lines and calculate width and height
StringTokenizer lines = new StringTokenizer( text, LINE_BREAK );
//The actual visual bounds of the characters
Rectangle2D visualBounds = font.createGlyphVector( fontRenderContext, text ).getVisualBounds();
//Line metrics (info on height, ascent, descent
LineMetrics metrics = font.getLineMetrics( text, fontRenderContext );
//Only have one line, so use GlyphVector
if ( lines.countTokens() == 1 )
     widest = ( int ) visualBounds.getWidth();
     totalHeight = ( int ) visualBounds.getHeight();
else
     while ( lines.hasMoreTokens() )
          String line = lines.nextToken();
          //Get boundary
          Rectangle2D bounds = font.getStringBounds( line, fontRenderContext );
          //Set the width
          widest = Math.max( widest, ( int ) bounds.getWidth() );
          //Add to the total height
          totalHeight += bounds.getHeight();
     //Need to remove any extra lineheight for last line (since is invisible)
     totalHeight -= ( int ) ( metrics.getHeight() - visualBounds.getHeight() );
//Set descent
descent = ( int ) metrics.getDescent();
//Adjust y for descent as Graphics draws a string from the baseline and we want the bottom
y = y + descent;
//Set width, height
width = widest;
height = totalHeight;

DarrylBurke wrote:
To get a more exact bounding rectangle, use TextLayout.
[http://forums.sun.com/thread.jspa?threadID=5241409]
dbThat's weird - it works! The problem is when i use the LineMetrics, the value it gives for getAscent() is actually the text's height! TextLayout has this correctly as the height.

Similar Messages

  • How get report of short text in tcode MCS3N ?

    Hello Experts,
    I need to provide report to the client listing Materials and corresponding bathes with short text (DFBATCH-KZTXT) and Shelf Life Exp. Date
    I understand from community that I can Use FM 'READ_TEXT' to get this values but the problem is it provides value for one record and need this information for about 500 records. Is there any better way to do this ?
    Please advise !
    Thanks,
    Darshak

    Hi,
    As my knowledge there is no other way to read, however this will retrieve the result very fast so there wont be any performance issue you can use this read_text FM within the loop.
    If its an format_message so we can achieve other way I suppose.
    Regards,
    Vadamalai A

  • How get Email description attribute text using C#

    I am Using CRM 2015 and Get Email activity attribute values but description
    attribute getting not text only it getting the whole Html.
    i just want to get the text only from description and set to Case Description.
    i am getting this value as
    string emailMessage = email.Attributes["description"].ToString();
    <html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns:m="http://schemas.microsoft.com/office/2004/12/omml" xmlns="http://www.w3.org/TR/REC-html40"><head><META
    HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=us-ascii"><meta name=Generator content="Microsoft Word 14 (filtered medium)"><style><!-- /* Font Definitions */ @font-face     {font-family:"Cambria
    Math";     panose-1:0 0 0 0 0 0 0 0 0 0;} @font-face     {font-family:Calibri;     panose-1:2 15 5 2 2 2 4 3 2 4;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal     {margin:0in;
        margin-bottom:.0001pt;     font-size:11.0pt;     font-family:"Calibri","sans-serif";} a:link, span.MsoHyperlink     {     color:blue;     text-decoration:underline;}
    a:visited, span.MsoHyperlinkFollowed     {     color:purple;     text-decoration:underline;} span.EmailStyle17     {     font-family:"Calibri","sans-serif";   
     color:windowtext;} .MsoChpDefault     {     font-family:"Calibri","sans-serif";} @page WordSection1     {size:8.5in 11.0in;     margin:1.0in 1.0in 1.0in 1.0in;} div.WordSection1
        {page:WordSection1;} --></style><!--[if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="1026" /> </xml><![endif]--><!--[if gte mso 9]><xml> <o:shapelayout
    v:ext="edit"> <o:idmap v:ext="edit" data="1" /> </o:shapelayout></xml><![endif]--></head><body lang=EN-US link=blue vlink=purple><div is Test Email 1<o:p></o:p></p><p
    Amatea<o:p></o:p></p></div></body></html>
    Muhammad Sohail

    Hello,
    Take a look here:
    Convert HTML to Plain Text for copying Email Message in CRM 2011 / 2013
    Hope it helps,
    Kind Regards

  • I have the iPhone 4. and when I updated the software to iOS6 My notifications don't make a sound anymore, the only sound that I get are text messages, or Email. I checked to see if the other apps were muted and they weren't. How do I fix this??

    I have the iPhone 4. and when I updated the software to iOS6 My notifications don't make a sound anymore, the only sound that I get are text messages, or Email. I checked to see if the other apps were muted and they weren't. How do I fix this

    You cannot update iPhone 4 to IOS 8.1.2, the highest you can update is IOS 7.1.2.
    Unless you've iPhone 4S (looks similar to iPhone 4)

  • I just upgraded to the new OS.  Now my wife and I are getting each others texts, and when we send a text to each other, it duplicates.  How can we separate our text messages?

    My wife and I are getting each other's text messages.  How do I turn that off so I get mine and she gets hers?

    On each Device, go to Settings>Messages>Send and Receive...  and make certain that each device only has 2-items with check marks your phone number and your email address.  click on the other persons number and email address such that it is not checked.

  • When I am on my home screen on the iPhone, swipe left to the search page. Put a letter in the search field. then scroll down. eventually you get to all your texts previously deleted or not. The are all there. How can I clear the entire text from the phone

    When I am on my home screen on the iPhone, swipe left to the search page. Put a letter in the search field. then scroll down. eventually you get to all your texts previously deleted or not. The are all there. How can I clear the entire text from the phone

    When I am on my home screen on the iPhone, swipe left to the search page. Put a letter in the search field. then scroll down. eventually you get to all your texts previously deleted or not. The are all there. How can I clear the entire text from the phone

  • How can I get rid of numbers that are covering my entire desktop, caused by right-clicking "Clean Up Selection" on an icon?

    How can I get rid of numbers that are covering my entire desktop, caused by right-clicking "Clean Up Selection" on an icon?  The Apple OS X Mavericks blue & green desktop is totally gone.  HELP!

    Here's a screenshot of my desktop, as of a few minutes ago:  http://lewgoodman.com/desktop.tiff

  • When all apps are closed the text vanishes from my toolbar.  How do i get it back?

    When all the apps are closed the text vanishes from the tool bar at the top of the screen.  The apple icon is still there on the far left but clicking on it does nothing.  I can't log out!!!!

    How do I find that out? I just switched to Apple and am finding it really hard to find stuff.

  • How are attribute and text master data tables linked in SAP R/3?

    Hello,
    how are attribute and text master data tables linked in SAP R/3?
    Most tables with attribute master data like T001 for company codes,
    have a text master data table T001T (add "T" to table name).
    When looking at the content of table T001 via transaction se11,
    the text are automatically joined.
    But for some tables there is no "T"-table (e.g. table TVBUR for sales offices
    has no text table TVBURT), but in se11 you get texts. There is an address
    link in TVBUR, but the Name1, etc. are empty.
    a) Where are the text stored?
    b) How does the system know of the link?
    Hope someone can help!
    Best regards
    Thomas

    Hi Thomas
    The master and text table are not linked by name, of course, if you see the text table, it has the same key fields of master table, only it has the field key spras and the field for description.
    The link beetween the tables is done by foreign key: if you check the text table TVKBT u need to see how the foreign key for field VKBUR is done:
    -> Foreing key with table TVBUR
    -> Foreing key field type -> KEY FIELD FOR A TEXT TABLE
    ->Cardinality-> 1-:CN
    It's very important the attribute sets for Foreing key field type, if it's KEY FIELD FOR A TEXT TABLE, it'll mean the table is a text table: i.e. that mean the master table is a check table for the text table, where the foreign key type is for text table.
    U can find out the text table of master table by SE11: GoTo->Text Table
    U can fined some information in table DD08L.
    Max

  • I upgraded pages.  Now when I begin a new document I automatically have a text box.  How do I get rid of the text box so that it does not automatically appear.  What settings do I need to change?

    I upgraded pages.  Now when I begin a new document I automatically have a text box.  How do I get rid of the text box so that it does not automatically appear.  What settings do I need to change?

    Perhaps you are loading a template that has a text block already on it.
    You might try the blank template option and set that as your go to template in your preferences

  • How to get the current location text in JTextPane

    hi
    i want to get the current location text in JTextPane ...iam useing
    caretPos = jtpMain.getCaretPosition();
    iam geting the current Locations at the same time i want to read the entery current line
    i used like this
    StartPos=jtpMain.getText();
    but iam geting entry data in JTextPane ... how can get current Locatin data ...
    pls help me

    If I understood your request, what you would like to do is to be able to retrieve Start and End Positions of a given line (a line and NOT the whole content of the JTextPane).
    JTextPane is a graphical component that is bound to a logical document. Documents are structured in elements. What defines an element is up to you to decide if you extend your own document but elements are by default paragraphs (runs of text ended by a carriage return '\n' character). So, I think that what you want to do is to retrieve the Start and End positions of the
    paragraph over which the caret is currently positionned. Then I think you have got to do the following :
    int intStartPos;
    int intEndPos;
    int intCaretPos;
    javax.swing.text.StyledDocument docStyledDoc;
    javax.wing.text.Element eleParagraph;
    intCaretPos = jtpMain.getCaretPosition( );
    //Get a reference to the default styled document bound to the JTextPane component
    docStyledDoc = jtpMain.getStyledDocument( );
    //Get the paragraph element from the document over which the caret is positionned
    eleParagraph = docStyledDoc.getParagraphElement(intCaretPos);
    //Get paragraph's offsets
    intStartPos = eleParagraph.getStartOffset( );
    intEndPos = eleParagraph.getEndOffset( );
    hi
    i want to get the current location text in JTextPane
    ...iam useing
    caretPos = jtpMain.getCaretPosition();
    iam geting the current Locations at the same time i
    want to read the entery current line
    i used like this
    StartPos=jtpMain.getText();
    but iam geting entry data in JTextPane ... how can
    get current Locatin data ...
    pls help me

  • How to get data of tabulated text file into internal table

    hi all,
    i want to get data from tabulated text file(notepad) into internal table. i searched in SCN and got lot of post regarding  how to convert excel file into internal table but i didnt get posts regarding text file.
    thanks
    SAchin

    try:
    DATA: BEGIN OF tabulator,
            x(1) TYPE x VALUE '09',
          END OF tabulator.
      READ DATASET file INTO wa.
    split wa at tabulator into table itab.
    A.

  • I downloaded a vector file from Shutterstock. How do I edit the text in Photoshop? If i enlarge the image- the pixels are awful and the image is distorted.

    i downloaded a vector file from Shutterstock. How do I edit the text in Photoshop? If i enlarge the image- the pixels are awful and the image is distorted.

    jessicae28493569 wrote:
    i downloaded a vector file from Shutterstock. How do I edit the text in Photoshop? If i enlarge the image- the pixels are awful and the image is distorted.
    What is the file format of the vector you downloaded?  Custom Shapes have a .PSP extension, and are placed according to this table.
    Preference filenames and locations in Photoshop CC
    They will then be loadable from the Custom Shapes drop down — click on the cog icon > Load shape > Find your downloaded vector.
    Once placed in the image, it will appear as a Shape layer, and can be edited with the Path, and Direct Selection tools (black and white arrows on the toolbar)

  • When I convert a file from PDF to word it is all in characters how do I get it in english text

    Please could someone help me with a converted file. I have bought the adobe acrobat and tried to convert my PDF to word and it just comes up with characters how to I get it in normal text?

    Hello,
    because you wrote in the Reader forum, so I think we talk about it, or? In my case I can change the text there (screenshot of my German AR):
    I hope the image is selfexplanatory and I understood you in the reight way. If not please come back to set right.
    Hans-Günter

  • How do you get a Node's text value using DOM?

    Hi,
    Can anyone tell me how I can extract the text values from <currency>, <Handle>, <shortcut> and <source> tags?
    This is my Code
    import org.w3c.dom.*;
    import org.apache.xerces.parsers.DOMParser;
    public class CurveConfSave{
    public static void walkover(Node n){
    if( n.getNodeType() == Node.ELEMENT_NODE){
         System.out.println("Walking over: " + ((Element)n).getNodeName());
         for( Node c = n.getFirstChild();c != null;c=c.getNextSibling()){
              walkover(c);
    public static void main(String[] args) {
    try {
    DOMParser p = new DOMParser();
    p.parse("CurveConf1.xml");
    Document doc = p.getDocument();
    NodeList liveCurvesNodeList = doc.getElementsByTagName("LiveCurves");
    System.out.println("Num items: " + liveCurvesNodeList.getLength());
    // Get the first node from the node list
    Node liveCurvesNode = liveCurvesNodeList.item(0);
    System.out.println("Live Curves Node: " + liveCurvesNode.getNodeName());
    walkover(liveCurvesNode);
    } catch (Exception ex) {
    System.out.println(ex);
    This is the xml chunk that I want to mainpulate
    <LiveCurves>
    <dd.enumerate>
    <AUD>
    <Currency>AUD</Currency>
    <Handle>GregB_AUD.today.</Handle>
    <Shortcut>LondonJava</Shortcut>
    <Source>XDB</Source>
    </AUD>
    </dd.enumerate>
    <dd.enumerate>
    <CAD>
    <Currency>CAD</Currency>
    <Handle>GregB_CAD.today.</Handle>
    <Shortcut>LondonJava</Shortcut>
    <Source>XDB</Source>
    </CAD>
    </dd.enumerate>

    This is the new modified code but I still get blanks for the Text Values I am trying to retrieve....
    import org.w3c.dom.*;
    import org.apache.xerces.parsers.DOMParser;
    public class CurveConfSave{
    public static void walkover(Node n){
    if( n.getNodeType() == Node.ELEMENT_NODE){
         System.out.println("Walking over: " + ((Element)n).getNodeName());
         for( Node c = n.getFirstChild();c != null;c=c.getNextSibling()){
              if("GBP".equals(c.getNodeName())){
                        NodeList childNodes = c.getChildNodes();
                        System.out.println("Child Nodes Length " + childNodes.getLength());
                        for (int i=0; i < childNodes.getLength();i++){
                        if(childNodes.item(i).getNodeType() == Node.ELEMENT_NODE){
                        System.out.println("Node value: " + "[" + childNodes.item(i).getNodeName() + "]");
                        if(childNodes.item(i).getNodeType() == Node.TEXT_NODE){
                        System.out.println("Node value: " + "[" + childNodes.item(i).getNodeValue() + "]");
                   System.exit(0);
              walkover(c);
    public static void main(String[] args) {
    try {
    DOMParser p = new DOMParser();
    p.parse("CurveConf1.xml");
    Document doc = p.getDocument();
    NodeList liveCurvesNodeList = doc.getElementsByTagName("LiveCurves");
    System.out.println("Num items: " + liveCurvesNodeList.getLength());
    // Get the first node from the node list
    Node liveCurvesNode = liveCurvesNodeList.item(0);
    System.out.println("Live Curves Node: " + liveCurvesNode.getNodeName());
    walkover(liveCurvesNode);
    } catch (Exception ex) {
    System.out.println(ex);

Maybe you are looking for

  • My HP Printer HP Officejet Pro 8600 Problem

    My printer is not scanning, faxing and copying. Once I press the copy option it give me an error message stating that "unable to scan, fax and copy".

  • Trouble scrolling on the main menu using my dvd player.

    I can't seem to move to the scenes button when I'm on the main menu using my DVD player. This function seems to work fine on my computer. Before I burn another (very long) disc and try again, does anyone have any suggestions? Natalie

  • Trying to re-add UPDATE and DELETE default buttons to a form

    I created a maintenance form by copying a form I use for inserting rows into a table. I deleted most of the form's default buttons. Now I'm trying to add the UPDATE and DELETE buttons to the cloned maintenance form, with no luck. When I look at the s

  • ExternalInterface.available returns true in standalone

    Incredibly frustrating - no matter what I try, in standalone test environment it always returns true - it should return false - any thoughts on this anyone. Its just ridiculous that Bugs like this occur....... Cheers,

  • Starfrfc.exe : Does SAPGUI need to be installed too?

    Hi. In the context of an interface, we are looking to use startrfc.exe to runa RFC enables function module. Now, simple question. Does SAPGUI have to be installed on the machine that runs the startrfc.exe ? Because at this point, startrfc.exe runs fi