gpt4 book ai didi

java - JButton.actionPerformed : null pointer exception

转载 作者:行者123 更新时间:2023-11-29 09:48:50 26 4
gpt4 key购买 nike

我正在阅读一本书,当单击 JButton 时,以下代码在运行时在 button.actionPerformed 行抛出 NPE。我已尽力确保我的代码与书中的完全一致,有人可以指出我的问题吗? (这本书是为 java 5 编写的,我使用的是最新的 java 7,据我所知,这对以下代码没有影响)

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

public class SimpleGui implements ActionListener {
JButton button;
public static void main(String[] args) {
SimpleGui gui = new SimpleGui();
gui.go();
}

public void go() {
JFrame frame = new JFrame();
JButton button = new JButton("click here");

button.addActionListener(this);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(button);
frame.setSize(300,300);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent event) {
button.setText("I've been clicked, argh!");
}

}

最佳答案

原因是这一行:

JButton button = new JButton("click here");

在这里您正在创建新的本地 JButton 对象,它是 shadowing成员变量 button 。因此 button 仍然是 null。您应该改用:

button = new JButton("click here");

关于java - JButton.actionPerformed : null pointer exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16255724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com