如何在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
相关产品推荐
相关产品推荐

