Link to home
Start Free TrialLog in
Avatar of TLTEO
TLTEO

asked on

sharing a common variable in 2 classes

I have 2 classes runnung 2 different ActionListener

How could I return a variable to the 1st class  after executing it in the second class.

Effectively, a need to call a second class because I need it to run an algorithm, but it uses AcionListener and I can't call a

return thisvariable to the first.

Is there a way to share the common variables between the 2 classes??

Hope you know what I mean?
Avatar of sengsational
sengsational

What I like to do is create a 'local memory' object.  This is a very simple class with all of the things I want in common (instance variables).  I instantiate one of these, and 'everybody' can read and write to it.  You just need to pass the reference to this object around to all of your classes.

--Dale--
i agree with sengsational .

create a class like this:

public class vars{

public static int var1=...
public static int var2...
}

and from another class cal the vars of this class and you will get what u need.

Nushi.
Avatar of TLTEO

ASKER

I have 2 class,  let's call class first and class second.

class first{
..
..
public void actionPerformed(ActionEvent e)
.
.
if(clickbutton==thisButton)
{
second sec= new second();
.
.
}


class second{
..
..
public void actionPerformed(ActionEvent e)
.
.
if(clickbutton==thisButton)
{
String thisvariable= getalgorithm(...)
.
.
}


How can I pass the string thisvariable  back to the first.class ??

I can use return method becos it is under void actionPerformed(...)





ASKER CERTIFIED SOLUTION
Avatar of superschlonz
superschlonz

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of TLTEO

ASKER

IC.   seems to be getting it now. I am happy that you understand what I meant. Tot I have read this method before but forgot. Let me test it and return to you again . Cheers superschlonz
Here's another way.  You pass a reference of the first class to the second.  That way you can run the setMyString method.  Or you could just make myString public and set it directly.

class first{
private String myString;
..
public void setMyString(String s){
myString = s;
}
..
public void actionPerformed(ActionEvent e)
.
.
if(clickbutton==thisButton)
{
second sec= new second(this);
.
.
}


class second{
private first otherclass;
// constructor
public second(first t){
otherClass = t;
}
..
..
public void actionPerformed(ActionEvent e)
.
.
if(clickbutton==thisButton)
{
String thisvariable= getalgorithm(...)
otherClass.setMyString(thisvariable);
.
.
}
Avatar of TLTEO

ASKER

tks to sensational too. great help cheers