This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Developer Certification (SCJD/OCMJD) and the fly likes static reference variable in GUI Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Developer Certification (SCJD/OCMJD)
Reply 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: 415
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: 415
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
Ranch Hand

Joined: Sep 13, 2007
Posts: 1222

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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: static reference variable in GUI
 
Similar Threads
? File I/O (and-or) for each loop
fixed element in gridbaglayout
make the last button align horizontally with other components
how to set this a borderq
GridBagConstraints Problem