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