Aurorachilles
Aurorachilles

Reputation: 81

How to declare a universal variable

I am building a GUI application in which I need to keep passing a single String to every JFrame. The method I am using is

frame2 frame 2 = new frame2(); 
String text = passabledata.getText();  //passabledata here is the name of the textField in frame1
frame2.jtextField1.setText(text);  //jTextField1 is public static TextField in frame2
frame2.setVisible(true);
this.setVisible(false);

I want to use a much more simpler method of passing and getting data

I was thinking about declaring a variable such that Every JFrame can use :

final String abc = (global variable name).getText();

and the global variable would be declared at the first GUI page using :

 private void jbutton1MouseClicked(java.awt.event.MouseEvent evt) 
 { 
   String text = username.getText();  //username is a jTextField                              
   (universal variable).setText(text);
 }      

Please help me out on how to do it.

Upvotes: 1

Views: 304

Answers (2)

Katy
Katy

Reputation: 1157

This is a common enough issue which you will face just about all the time in the development life.

While there are a few ways you might do this, you have to appreciate which ones are going to serve you in the long run.

As a general rule of thumb, like most programming languages, global variables (in this case static variables) represent a risk and are generally a sign of bad design. Generally speaking you should avoid them where ever possible and use other techniques. The more complex a program becomes, the easier it will be to completely screw up your state.

The simplest solution would be to simply pass the information that you other classes are interested to them directly, either via the class constructor or via a method call. See Passing Information to a Method or a Constructor for more details

There are other approaches, such as Observer Pattern, producer/consumer and other behavioral patterns which would also be applicable, but they work on the basic principle of passing information via a method/function call.

Upvotes: 2

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

You will want to pass at least one variable to the constructor of every frame. This variable can then have fields for whatever you may need.

It's unfortunate that Java is highly verbose when it comes to constructing objects, unless you use local/anonymous inner classes or lambda expressions.

Don't use global state (a.k.a. statics).

Upvotes: 2

Related Questions