You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LibGDX中正确放置三个方形元素

问题解决:LibGDX 三个方形元素布局对齐

问题分析

当前代码中,第二行的两个小正方形直接添加到根Table后,因根Table行默认左对齐,导致它们无法与上方大正方形居中对齐,不符合预期布局。

解决方案

把下方两个小正方形放入子Table中,再将子Table添加到根Table的第二行,子Table会自动与上方大正方形居中对齐。可按需添加间距优化布局:

修改后的核心代码:

@Override
public void create() {
    stage = new Stage(new ScreenViewport());
    Gdx.input.setInputProcessor(stage);

    Table root = new Table();
    root.setFillParent(true);
    stage.addActor(root);

    Image button = new Image(createTexture(Color.ROYAL, 300,300));
    Image button2 = new Image(createTexture(Color.ROYAL, 200,100));
    Image button3 = new Image(createTexture(Color.ROYAL, 200,100));

    // 上方大正方形居中对齐
    root.add(button).center();
    root.row();
    
    // 子容器放置两个小正方形
    Table bottomContainer = new Table();
    bottomContainer.add(button2).width(200);
    // 添加间距,可根据预期效果调整数值
    bottomContainer.add(button3).width(200).padLeft(20);
    
    // 子容器加入根Table,自动居中
    root.add(bottomContainer).center();

    root.setDebug(true);
}

其他可选调整

若不想使用子Table,也可直接设置根Table的对齐约束:

root.add(button).center();
root.row();
// 让两个小正方形单元格居中,并添加间距
root.add(button2).width(200).center();
root.add(button3).width(200).center();
root.getCell(button2).spaceRight(20);
root.row().center();

内容的提问来源于stack exchange,提问作者napastnikiek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 07:32:10