• Post Reply Bookmark Topic Watch Topic
  • New Topic

a strange problem for NullPointerException by using JButton  RSS feed

 
yue kang
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
today, I write a very simple gui,but a strange question appears.

the problem program as follow:

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

public class SimpleGui1B implements ActionListener{
[color=red]JButton button3;

public static void main(String args[]){
SimpleGui1B gui=new SimpleGui1B();
gui.go();
}

public void go(){
JFrame frame=new JFrame();
JButton button3=new JButton("click me");
button3.addActionListener(this);


frame.getContentPane().add(button3);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);

}

public void actionPerformed(ActionEvent event){

button3.setText("I've been clicked");

}
}[/color]



I run that, but turn out the nullpointer error..

but i did a little change as follow:


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

public class SimpleGui1B implements ActionListener{
[color=red]JButton button3;
JButton button2;

public static void main(String args[]){
SimpleGui1B gui=new SimpleGui1B();
gui.go();
}

public void go(){
JFrame frame=new JFrame();
JButton button3=new JButton("click me");
button2=button3;
button3.addActionListener(this);


frame.getContentPane().add(button3);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(300,300);
frame.setVisible(true);

}

public void actionPerformed(ActionEvent event){

button2.setText("I've been clicked");

}
}
[/color]



I only use button2 to replace button3..and everything is ok.......
i wonder how it goes...
can you tell me what happened..
 
K. Tsang
Bartender
Posts: 3648
16
Firefox Browser Java Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your button3 in the first code listing is a local variable inside the go() method.
 
Rob Spoor
Sheriff
Posts: 21092
85
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you UseCodeTags next time, you get syntax highlighting and line numbering for three. No need for all these color blocks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!