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

如何在ActionListener中通过点击的JButton调用getClientProperty()获取编号

解决Sudoku按钮编号获取问题

首先你的代码存在一个关键问题:button1到button9仅做了声明但未实例化,直接放入数组bArr后,数组内的元素全为null,运行时会抛出NullPointerException。先修正这个问题,再实现点击按钮获取编号的功能。

以下是完整的修正代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SudokuFeld extends JFrame{
    private JPanel secondaryPanel;
    private JButton button1 = new JButton();
    private JButton button2 = new JButton();
    private JButton button3 = new JButton();
    private JButton button4 = new JButton();
    private JButton button5 = new JButton();
    private JButton button6 = new JButton();
    private JButton button7 = new JButton();
    private JButton button8 = new JButton();
    private JButton button9 = new JButton();
    private JButton[] bArr = new JButton[] {button1, button2, button3, button4, button5,button6, button7, button8, button9};
    
    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 获取触发事件的按钮对象
            JButton clickedButton = (JButton) e.getSource();
            // 获取预先设置的编号
            Integer buttonNumber = (Integer) clickedButton.getClientProperty("number");
            // 输出编号
            System.out.println("点击的按钮编号:" + buttonNumber);
        }
    };


    public SudokuFeld() throws HeadlessException {
        // 初始化窗口布局,让按钮正常显示
        secondaryPanel = new JPanel(new GridLayout(3,3));
        int var = 0;
        for(JButton val : bArr ) {
            val.putClientProperty("number", var);
            val.addActionListener(listener);
            secondaryPanel.add(val);
            var++;
        }
        this.add(secondaryPanel);
        this.setSize(300,300);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new SudokuFeld();
    }
}

关键说明:

  • 实例化按钮:给每个button1到button9添加new JButton()初始化,避免空指针异常。
  • 获取点击按钮:在actionPerformed方法中,通过e.getSource()获取触发事件的按钮实例,强制转型为JButton。
  • 读取编号:调用getClientProperty("number")获取之前存入的编号,注意转型为Integer类型。
  • 窗口布局:添加GridLayout布局并将按钮加入面板,确保按钮能在窗口中显示,方便测试点击功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:55:18