gpt4 book ai didi

java - 如何将大字体的 LabelField 居中

转载 作者:太空宇宙 更新时间:2023-11-04 08:03:28 25 4
gpt4 key购买 nike

我需要使用垂直字段管理器将 LabelField 水平居中。我还需要增加这个 LabelField 的字体大小。我发现,一旦使用 FIELD_HCENTER 将其居中,如果更改字体大小,它就会更改字段的位置。

这是代码

VerticalFieldManager vfm = new VerticalFieldManager(Field.FIELD_VCENTER | Manager.USE_ALL_WIDTH);
LabelField title = new LabelField("My Title",Field.FIELD_HCENTER) ;
title.setFont(Font.getDefault().derive(Font.BOLD, 18, Ui.UNITS_pt);
vfm.add(title);

(如果我删除第三行 title.setFont,则标题居中,否则不居中)。我需要一些帮助才能找到解决方案。有什么帮助值得赞赏吗?谢谢

最佳答案

您可以通过重写 VerticalFieldManagersublayout 方法来创建自定义 FieldManger,这会将其子项置于中心。下面就是这样的一个实现。

class CustomVerticalFieldManger extends VerticalFieldManager {
private final int VERTICAL_GAP = 30;

protected void sublayout(int maxWidth, int maxHeight) {
int nFields = getFieldCount(), height = 0, xPosition, yPosition = 0;
Field f;
for (int i = 0; i < nFields; i++) {
f = getField(i);
layoutChild(f, maxWidth, maxHeight);
height += f.getHeight();
if (i != 0) {
height += VERTICAL_GAP;
}
}
for (int i = 0; i < nFields; i++) {
f = getField(i);
xPosition = (maxWidth - f.getWidth()) / 2;
setPositionChild(f, xPosition, yPosition);
yPosition += f.getHeight();
if (i != nFields - 1) {
yPosition += VERTICAL_GAP;
}
}
setExtent(maxWidth, height);
}
}

用法

class MyScreen extends MainScreen {
private LabelField lblOne, lblTwo, lblThree;

public MyScreen() {
CustomVerticalFieldManger cvfm = new CustomVerticalFieldManger();
cvfm.setBackground(BackgroundFactory.createSolidBackground(Color.AQUA));

lblOne = new LabelField("The quick brown fox jumps over the lazy dog");
lblTwo = new LabelField("The quick brown fox jumps over the lazy dog");
lblThree = new LabelField("The quick brown fox jumps over the lazy dog");

cvfm.add(lblOne);
cvfm.add(lblTwo);
cvfm.add(lblThree);

add(cvfm);

changeFont();
}

private int fontSize = 5;

private void changeFont() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
if (fontSize == 50) {
fontSize = 5;
}
lblOne.setFont(Font.getDefault().derive(Font.PLAIN,
fontSize));
lblTwo.setFont(Font.getDefault().derive(Font.PLAIN,
fontSize + 2));
lblThree.setFont(Font.getDefault().derive(Font.PLAIN,
fontSize + 4));
fontSize += 6;
updateLayout();
invalidate();
}
});
}
};

timer.schedule(task, 500, 1000);
}
}

关于java - 如何将大字体的 LabelField 居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12463007/

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