为什么点击按钮的时候报错了

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class Gui01 implements ActionListener{

JButton btn;

public static void main(String[] args) {

Gui01 gui = new Gui01();

gui.go();

}

public void go(){

//创建JFrame

JFrame frame = new JFrame("my first Gui");

//创建按钮

JButton btn = new JButton("click me");

//在window结束时,把程序结束

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//为按钮添加事件监听

btn.addActionListener(this);

//把button添加到frame 的 pane上

frame.getContentPane().add(btn);

//设置frame的大小

frame.setSize(500,500);

//显示frame

frame.setVisible(true);

}

//此方法为事件响应的回调函数

public void actionPerformed(ActionEvent e){

System.out.println("hello world");

try{

btn.setText("i've been clicked.");

}catch(Exception ex){

ex.printStackTrace();

}

}

}


一个爱狗的男生
浏览 1387回答 2
2回答

朕日理万机

你在类里面声明了一个成员变量:JButton btn;然后在go方法里面声明了一个局部变量JButton btn = new JButton("click me");局部变量就把成员变量屏蔽了,你实际上添加到JFrame里面的是这个局部的btn,而不是类成员btn。局部btn出了go方法就不再被认得了,而actionPerformed方法里面的btn会认为是类成员btn,该成员并没有被初始化,所以抛出空指针异常。两种解决方法:第一是去掉go方法里的声明语句,改为初始化语句(看起来这是你的本意):btn = new JButton("click me");二是actionPerformed中不要调用成员变量btn,而是改为通过e来判断到底哪个按钮被按了:((AbstractButton) e.getSource()).setText("i've been clicked.");还有个小建议,以后尽量贴出错误信息,这样回答的人更容易看明白;-)

慕瓜9220888

BCUECZPCFMNWHIRHORWUCHZTVVPPNLDSFRLOUVQSUKERDGOQSDWZUKVPVWIORUEAOAOQQNMMBDFUXERILCHGVKRYFPNSVCVVCDNHFJSBCPTTDLEKZPQXLTIHZIPQGHSHGZRAQKVWRDMVWQWHCKOEDAHYBLUCVYOSZZUIHYNEGKEYRQTSZPGXKLOQJAUKEWETMFMCJDTYVLVSPNNPAZADURISFEVEDTKUYPXZPYVFCPVKWFOOFVPFTCRQXODUMGZLFANETVUWFOBCSTABKTSJZGQYTYOWFJ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