0

我正在开发一个应用程序,其中 9i 已经参加CustomeButtonField了制作自定义按钮的课程。其中我得到了自定义按钮,但文本按钮未对齐中心。您能否让我知道在 CustomeButtonFiel 中如何将按钮文本设置为中心。

这是代码

import net.rim.device.api.system.Bitmap;
import net.rim.device.api.ui.*;

public class CustomButtonField extends Field
{
    Bitmap Unfocus_img, Focus_img, current_pic;
    int width;
    String text;
    Font font;   
    int custColor;
    CustomButtonField(int width, String text, Bitmap onFocus, Bitmap onUnfocus, long style,int custColor)
    {
        super(style);
        Unfocus_img = onUnfocus;
        Focus_img = onFocus;
        current_pic = onFocus;
        this.text = text;
        this.width = width;
        this.custColor = custColor;
    }
    protected void layout(int width, int height) 
    {
        setExtent(current_pic.getWidth(), current_pic.getHeight());        
    }
    protected void paint(Graphics graphics) 
    {
        try
        {
                FontFamily fntFamily = FontFamily.forName("BBAlpha Sans");
                font = fntFamily.getFont(Font.BOLD,20);              
        }
        catch(Exception e)
        {
            font = Font.getDefault();

        }
        graphics.setFont(font);


        graphics.setColor(custColor); 


        graphics.drawBitmap(0, 0, current_pic.getWidth(), current_pic.getHeight(), current_pic , 0 , 0);
        graphics.drawText(text, width, 7);
        graphics.setDrawingStyle(Graphics.HCENTER, true);
    }
    protected void onFocus(int direction) 
    {
        super.onFocus(direction);
        current_pic = Unfocus_img;
        this.invalidate();
    }
  protected void drawFocus(Graphics graphics, boolean on) 
  {

    }
    protected void onUnfocus() 
    {
        super.onUnfocus();
        current_pic = Focus_img;
        invalidate();
    }
    public boolean isFocusable() {
        return true;
    }
    protected boolean navigationClick(int status, int time) {
        fieldChangeNotify(0);
        return true;
    }
} 
4

1 回答 1

2

将方法的最后 3 行替换为paint以下行:

int xText = (getWidth() - font.getAdvance(text)) / 2;
int yText = (getHeight() - font.getHeight()) / 2;

graphics.drawBitmap(0, 0, current_pic.getWidth(), current_pic.getHeight(), current_pic , 0 , 0);
graphics.drawText(text, xText, yText);
于 2012-07-30T10:00:59.197 回答