Using values in different classes
Okay, I'm wondering if it's possible to use a value from one class in another class. Specifically, a JTextField value. I think I know how to do it normally:
Code :
First class:
public String textFieldValue()
{
return x;
}
Second class:
System.out.println(FirstClass.x);
But in my code, a button must first be pressed (using an action listener) to get the JTextField values. This means that I have to use this:
Code :
public void actionPerformed(ActionEvent e) {
//get JTextField values
}
As you probably know, you can't return any values within a void method so I have no idea how to get these values to another class.
Re: Using values in different classes
I'm a bit unclear on the question, so perhaps more code is in order. If you follow encapsulation guidelines, variables will be private and accessed via getters and setters
Code :
//Demo class with a single private variable
public class A{
private int val = 0;
public int getVal(){
return val;
}
}
//Demo class which accesses A
public class B{
A a = new A();
public void function(){
int val = a.getVal();
//do something with val
}
}
Re: Using values in different classes
Hi Copeg, I believe you helped me with my other problem :) The code you showed I understand, however my problem is a bit different. I want to get a variable (which happens to be under a void method, so I can't return its value) to be accessible by another class. I don't know how to do this for the exact reason I mentioned in the parenthesis. Putting "public" in front of the variable doesn't do anything because the value for that variable changes after I run the class.