This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Referencing a public variable... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Referencing a public variable..." Watch "Referencing a public variable..." New topic

Referencing a public variable...

Nick Davies

Joined: Apr 22, 2005
Posts: 3
Hi there, I have a rather silly question, however its got the better of me!

This is simple example of the work I'm doing:

I have a variable:

public String varname;

and it stores some text.

How do i reference that variable in another form? For example, I have a label in a seperate form.

JLabel mylabel = new JLabel();

How do I get it to display the text from the variable (varname) in the other form


^^ This doesn't work. How do i reference the variable correctly?

Help much appreciated
marc weber

Joined: Aug 31, 2004
Posts: 11343

When you say, "in a separate form," I'm assuming this means in a different class. If so, you'll need to reference an instance of the class containing the variable. For example...


...where "myInstance" is an instance of the class in which varname is defined.

(Otherwise, please post the error message you're getting.)

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
Nick Davies

Joined: Apr 22, 2005
Posts: 3
Thanks for your reply. Yeah sorry, i meant a seperate class not form.

The error it gives me is:

Any suggestions?

marc weber

Joined: Aug 31, 2004
Posts: 11343

It appears that the variable is actually within scope. The problem is that you're trying to access an instance variable from a static context (probably a main method).

Basically, the solution is the same: You need to use a reference to an instance that contains the variable.
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

You could also declare the public variable to be static:

Of course if you do this, all instances of SomeClass.varName will be pointing to the same String object.
[ April 27, 2005: Message edited by: Ben Souther ]

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
I agree. Here's the link:
subject: Referencing a public variable...
Similar Threads
Set the label size
Do I have the chance to use a String Constant as a Varible Name?
a simple question about Form Bean setter method
Reference to ActionForm in jsp
JLabels and setText()