Reputation: 590
I am using a JFrame which accepts a value from the user and stores it in a variable (filePath). I want to use this value in another class. How can i hold the value from the JFrame and use it in another class?
JFrame code:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Specify a file to save");
int userSelection = fileChooser.showSaveDialog(this);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile();
String filePath = fileToSave.getAbsolutePath();
}
Class code:
String filename="";
I want to get the filePath value into filename String.
Any help?
Upvotes: 0
Views: 2083
Reputation: 687
You can create a static method in that class where you want to hold the value. eg.
class Get {
static String filename;
public static void getValue(String value) {
filename = value;
}
}
Then once you get the file path from.
String filePath = fileToSave.getAbsolutePath();
Just after that call the static method of the other class. For instance in my case that class is Get.
Get.getValue(filePath);
OR Crete a constructor of the class that gets a string value.
class Get {
String filename;
Get(String value) {
filename = value;
}
}
}
While creating the object of the class, Send that value to the constructor.
Get g = new Get(filePath);
And even simpler. Introduce a static variable in the holder class, from the jframe class set its value to filepath.
class Get {
static String filename;
}
Then just set the value of the filename to the filePath as below.
Get.filename = filePath;
Upvotes: 1
Reputation: 61
There are several ways to pass the parameter to another class. You haven't said much of the context of your problem, maybe You could write little more about it.
Nevertheless here are few ways:
Let say You get this string in class A and want to pass it to class B.
Make filename
variable public property in class A, than class B can access that property if it has reference to class A. This is probably the worst solution because B has to have reference to class A and B must wait for it's turn to get this property.
Better solution is to implement Observer pattern where A is subject and B is observer. This is best solution if You need to pass string immediately after you get it from JFileChooser.
Another solution will be to store string in Singleton object that all classes have access to.
In my opinion, latter two solutions are preferred ones. But it all depends on context of the problem and complexity of your app (maybe there is no need to complicate code with patterns).
Upvotes: 0