i'm a beginner in Java, and i'm doing a Java project right now. What i should do is : when i click on button1, i choose a folder and i get the path of this folder saved in the variable fullpath.
And in the second action, when i click on the button2 i would like to create a new file with the same path that i got from the first button.
i think the problem is in the variable fullpath.
i know the question is not very clear, but i tried my best.
Thanks Guys.
if (event.getSource() == Importer) {
JFileChooser chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal =chooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
String fullpath= chooser.getSelectedFile().getAbsolutePath();
System.out.println(fullpath);
}
}
if (event.getSource() == Valider) {
File path= new File(fullpath);
File[] allFiles = path.listFiles();
}
Java Scoping issue
While there may be other unknown issues with your code, one definite problem is with scoping issues: you have a variable declared in a local region of the code and only visible within that region, while meanwhile, your program needs the information that that variable holds elsewhere within the program.
Specifically, you're declaring full path variable within an if block that is nested inside the listener:
So as declared like this:
Per Java scoping rules, the
fullpathvariable is visible within the if block and only within the if block. If you need to use it elsewhere in the class, it should be declared as a field of the class:Now the
fullpathvariable, and the information that it might hold, is visible throughout the code