aspose file tools*
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes static reference variable in GUI Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Bookmark "static reference variable in GUI" Watch "static reference variable in GUI" New topic
Author

static reference variable in GUI

Leandro Coutinho
Ranch Hand

Joined: Mar 04, 2009
Posts: 417
Hi!

I think that all fields (variables) related with the GUI must be static, am I right?
Because there is no reason to have more than one instance of the same object, like label, button, and the frame.

Here is an example:
What do you think?
John Sutt
Ranch Hand

Joined: Mar 07, 2008
Posts: 42
Hi Leandro,

I tend to disagree with you.

Making the variables static will only make sure that the program does not work correctly if the
GridBag2 class is instantiated multiple times.
For example, the txtName textfield probably is editable by the user. You don't want this to be
static!

(If you really want to enforce there is a single instance at most, you could use the Singleton pattern.)

I would make none of those variables static.

SCJP 6 (91%), SCJD (91%)
Leandro Coutinho
Ranch Hand

Joined: Mar 04, 2009
Posts: 417
Thanks for your reply.
John Sutt wrote:
For example, the txtName textfield probably is editable by the user. You don't want this to be
static!

Why not?
John Sutt
Ranch Hand

Joined: Mar 07, 2008
Posts: 42
I tested it now with the below program.
In case the JTextField tf is static, it did not show up in the second JFrame.
If you remove the "static", it works fine.

K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2409
    
    7

Hi John, from what I understand the static variable and where to instantiate the component is 2 seperate unrelated issues. If you declare and instantiate the Swing JTextField as instance variable for a dialog box, the 2nd time you load it this JTextField component will not re-instantiate meaning you can see the original text entered before. Therefore declare it but don't instantiate it until inside the methods - then you won't get this problem.


K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static reference variable in GUI