• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Referencing a public variable...

 
Nick Davies
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

mylabel.setText(varname);

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

Help much appreciated
Nick
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...

mylabel.setText(myInstance.varname);

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

(Otherwise, please post the error message you're getting.)
 
Nick Davies
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply. Yeah sorry, i meant a seperate class not form.

The error it gives me is:



Any suggestions?

Nick
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic