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

使用JLabel数组和GridBagLayout制作6*8棋盘调用setText报空指针错误

问题原因

你声明二维JLabel数组时,仅完成了数组容器的初始化,Java中引用类型数组初始化后所有元素默认值都是null,你没有对每个JLabel元素做实例化就直接调用setText()方法,因此触发空指针异常。

修复方案

在循环内部先为每个template[i][j]实例化JLabel对象,再进行赋值和添加操作即可,修改后的initialize()方法代码如下:

private void initialize() {
    frame = new JFrame();
    frame.getContentPane().setBackground(Color.WHITE);
    
    templatePanel = new JPanel();
    
    templatePanel.setBackground(Color.WHITE);
    frame.getContentPane().add(templatePanel, BorderLayout.CENTER);
    GridBagLayout g = new GridBagLayout();
    GridBagConstraints gbc = new GridBagConstraints();
    templatePanel.setLayout(g);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 8; j++) {
            // 新增JLabel实例化逻辑,也可直接写为new JLabel("_")省略单独调用setText的步骤
            template[i][j] = new JLabel();
            template[i][j].setText("_");
            gbc.gridx = j;
            gbc.gridy = i;
            templatePanel.add(template[i][j], gbc);
        }
    }
    frame.setBounds(100, 100, 450, 300);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:06:00