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

如何将JButton排列为窗口顶部的两行对称布局?

实现顶部两行对称按钮布局

要让所有按钮在窗口顶部呈两行对称排列,核心是用GridLayout统一管理按钮布局,替代原来拆分的三个面板。以下是修改后的完整代码:

package com.company;

import javax.swing.*;
import java.awt.*;

class Fantasyrpglifesim {
    private static int count = 1;

    public static void main(String[] args) {
        JFrame frame = new JFrame();
        // 创建顶部面板,设置2行6列布局,行列间距10像素
        JPanel topPanel = new JPanel(new GridLayout(2, 6, 10, 10));
        // 给按钮设置统一最小尺寸,避免拉伸过度
        Dimension btnSize = new Dimension(120, 30);

        // 创建所有按钮并设置尺寸
        JButton age = new JButton("Age up");
        age.setMinimumSize(btnSize);
        JButton character = new JButton("Character");
        character.setMinimumSize(btnSize);
        JButton worldmap = new JButton("World map");
        worldmap.setMinimumSize(btnSize);
        JButton settings = new JButton("Settings");
        settings.setMinimumSize(btnSize);
        JButton jobs = new JButton("Jobs");
        jobs.setMinimumSize(btnSize);
        JButton management = new JButton("Management");
        management.setMinimumSize(btnSize);
        JButton family = new JButton("Relationships");
        family.setMinimumSize(btnSize);
        JButton crafting = new JButton("Crafting");
        crafting.setMinimumSize(btnSize);
        JButton newgame = new JButton("New game");
        newgame.setMinimumSize(btnSize);
        JButton tutorial = new JButton("Tutorial");
        tutorial.setMinimumSize(btnSize);
        JButton log = new JButton("Log");
        log.setMinimumSize(btnSize);
        JButton achievements = new JButton("Achievements");
        achievements.setMinimumSize(btnSize);

        // 将按钮按顺序添加到顶部面板,自动填充2行6列
        topPanel.add(age);
        topPanel.add(character);
        topPanel.add(worldmap);
        topPanel.add(settings);
        topPanel.add(jobs);
        topPanel.add(management);
        topPanel.add(family);
        topPanel.add(crafting);
        topPanel.add(newgame);
        topPanel.add(tutorial);
        topPanel.add(log);
        topPanel.add(achievements);

        // 将顶部面板添加到窗口北部
        frame.getContentPane().add(BorderLayout.NORTH, topPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 让窗口组件自适应布局
        frame.pack();
        frame.setVisible(true);
    }
}

关键修改点:

  1. 替换布局容器:删除原来的mainPanel/westPanel/eastPanel,改用一个topPanel并设置GridLayout(2, 6, 10, 10),指定2行6列,同时设置按钮间的水平/垂直间距为10像素,保证视觉对称。
  2. 统一按钮尺寸:给所有按钮设置相同的最小尺寸,避免GridLayout拉伸导致按钮大小不一。
  3. 简化层级:所有按钮直接加入topPanel,无需拆分多个面板,布局逻辑更清晰。
  4. 使用pack():替代固定窗口大小,让窗口根据组件尺寸自动调整,避免布局错位。

如果需要调整每行按钮数量(比如每行4个、3行),只需修改GridLayout的参数为new GridLayout(3, 4, 10, 10)即可,灵活性很高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 05:41:18