• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

understanding simple gui code

Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();

public void go()
JFrame frame = new JFrame();
button = new JButton("click me");


frame.setSize(300, 300);

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.
Ranch Hand
Posts: 694
Mac OS X Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.

This cake looks terrible, but it tastes great! Now take a bite out of this tiny ad:
the value of filler advertising in 2021
    Bookmark Topic Watch Topic
  • New Topic