This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

understanding simple gui code

 
Imtiaz Nizami
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 689
Eclipse IDE Firefox Browser Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic