The following code is a straight copy from "Head First Java" which I am reading currently.
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1B implements ActionListener
{
JButton button;
public static void main (
String [] args)
{
SimpleGui1B gui = new SimpleGui1B();
gui.go();
}
public void go()
{
JFrame frame = new JFrame();
button = new JButton("click me");
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
button.setText("I've been clicked!");
}
}
I have a question regarding scope (I think). "button" here is an instance reference variable so it exist as long as object exists. When a call to method "go()" is made a frame is created. Now frame is local to the method "go()". Then when method "go()" exits should not the frame disappear?
I am sure I am missing something basic and important here. The gui sits there as if there is some kind of loop calling the function again and again. But this analogy is not true as well because if I click the button, text changes and remains changed. If the function call is being made repeatedly then the text should be the default "click me" always. So what really is going on? Please help.