为什么我的TableLayout无法将组件居中?我只在单列中放置了几个组件,希望它们居中,但是TableLayout的居中约束似乎在这种情况下不起作用。需要说明的是,我也尝试过BoxLayout,但是我没有看到任何可以将组件居中的方法。此外,我计划在下面添加更多组件,所以BorderLayout不可行。以下是它的样子,与我在Android手机上看到的一样。
public class Playground {
private Form current;
private Resources theme;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
}
public void start() {
if (current != null) {
current.show();
return;
}
Form hi = new Form("Table Layout Test");
TableLayout layout = new TableLayout(4, 1);
hi.setLayout(layout);
// I specify row and column explicitly or the replaceAndWait() method will put the
// replacement below the button instead of above it.
TableLayout.Constraint center;
center = layout.createConstraint(0, 0).horizontalAlign(hi.CENTER);
red = new Label(makeBlankImage(200, 200, 0xFF0000));
blue = new Label(makeBlankImage(200, 200, 0xFF));
visibleLabel = red;
hi.add(center, visibleLabel);
center = layout.createConstraint(1, 0).horizontalAlign(hi.CENTER);
Button button = new Button("Switch");
button.addActionListener(evt -> {
Label priorImage = visibleLabel;
//noinspection ObjectEquality
if (visibleLabel == red) {
visibleLabel = blue;
} else {
visibleLabel = red;
}
hi.replaceAndWait(priorImage, visibleLabel, CommonTransitions.createFade(500));
});
hi.add(center, button);
center = layout.createConstraint(2, 0).horizontalAlign(hi.CENTER);
Label label = new Label("Why aren't any of these");
hi.add(center, label);
center = layout.createConstraint(3, 0).horizontalAlign(hi.CENTER);
SpanLabel label2 = new SpanLabel("components centered?");
hi.add(center, label2);
hi.show();
current = hi;
}
private Label red;
private Label blue;
private Label visibleLabel;
private Image makeBlankImage(final int width, final int height, int color) {
Image image = Image.createImage(width, height);
Graphics graphics = image.getGraphics();
graphics.setColor(color);
graphics.fillRect(0, 0, width, height);
return image;
}
public void stop() {
}
public void destroy() {
}
}