gpt4 book ai didi

java - 使自定义按钮的中心文本

转载 作者:行者123 更新时间:2023-12-02 07:40:10 25 4
gpt4 key购买 nike

我正在开发一个应用程序,其中 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;
}
}

最佳答案

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

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);

关于java - 使自定义按钮的中心文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11718832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com