File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes understanding simple gui code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "understanding simple gui code" Watch "understanding simple gui code" New topic
Author

understanding simple gui code

Imtiaz Nizami
Greenhorn

Joined: May 19, 2007
Posts: 12
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.
Kaydell Leavitt
Ranch Hand

Joined: Nov 18, 2006
Posts: 689

I believe that the JFrame object is passed to the event-dispatch thread when setVisible(true) is called. So there is still a reference to the JFrame and it doesn't go away.

go() is called only once, so the button name doesn't change back to its initial value.

Kaydell
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: understanding simple gui code