The letter 'p' showing its 'reference point' When an application asks to place a character at the position (x, y), the character is placed so that its reference point (shown as the dot in the accompanying image) is put at that position. The reference point specifies a horizontal line called the baseline of the character. In normal printing, the baselines of characters should align.


fm.getStringBounds(String, Graphics)

Returns the bounds of the specified String in the specified Graphics context. The bounds is used to layout the String.

This method can be used to get text location information.

Note: The returned bounds is in baseline-relative coordinates


Sample, HyperLink Button, the important code:

    public void paintComponent(Graphics g) {
        if(getAction() == null){
        Font f = getFont();
        FontMetrics fm = g.getFontMetrics(f);
        Rectangle2D b1 = fm.getStringBounds(getText(), g);
        // Get the line location.
        double baseY = getHeight() - (getHeight() - b1.getHeight())/2 -1 ;
        double baseX = (getWidth() - b1.getWidth())/2;
        int length =(int)b1.getWidth();
        g.drawLine((int)baseX, (int)baseY, (int)baseX+ length, (int)baseY);
        if (onFocus) {
            double recY = getHeight()/2 - fm.getAscent()/2;
            GraphicUtil.drawDashedRect(g,(int)baseX, (int)recY-1, length, (int)b1.getHeight());
Technorati 标签: