Trouble returning text height

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • HxRLxY
    New Member
    • Sep 2008
    • 23

    Trouble returning text height

    I am trying to create custom buttons for an application. I have created a class that extends JButton and overridden the paintComponent( ) method. My problem is that I cannot find a way to return the pixel height of the text that will be put on the button, and therefore I am not able to center the text vertically within the button. I have tried something like this:

    Code:
    GlyphVector gv = myFont.createGlyphVector (g2d.getFontRenderContext(), string);
    double height = gv.getLogicalBounds().getHeight();
    
    textLocationY = (myButton.getHeight() + height) / 2;
    g2d.drawString (string, textLocationX, textLocationY);
    I have also tried using FontMetric and calling getHeight, getAscent, getMaxAscent, etc... I can get the text almost centered, but it is still visibly off. I can center the text by hard-coding a couple of extra pixels, but that doesn't hold when the button is resized, or if I change the font size, and it's just bad programming practice. Any help would be greatly appreciated.
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Get the ascent from the LineMetrics object given a piece of text using a Font (read the API documentation of the Font class). Note that long ascenders (e.g. h, k, l and the capital letters) cause the entire text to be visually positioned a bit lower than you expected because the majority of the pixels will be positioned below the average height. If you want to correct that you really have to do quite some ugly calculations.

    kind regards,

    Jos

    Comment

    • HxRLxY
      New Member
      • Sep 2008
      • 23

      #3
      I found that using TextLayout and calling getBounds returns a fairly accurate bounding rectangle. Thank you for the help.

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by HxRLxY
        I found that using TextLayout and calling getBounds returns a fairly accurate bounding rectangle. Thank you for the help.
        Yes, a TextLayout object uses a LineMetrics object to do the dirty work.

        kind regards,

        Jos

        Comment

        Working...