• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static reference variable in GUI

 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Leandro Coutinho
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3526
16
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic