JFileChooser for passing selected file into argument of different class object - java

in my main class I have this method
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TxtFileFilter());
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File f = fileChooser.getSelectedFile();
}
}
I want to pass the selected file into the argument of an object in another class of the same project and package:
public class ImportFile {
File fileToImport = new File("C:/data/myData.txt");//path will be set from GUI
How to do this? Thanks!

You can do someting like this:
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new TxtFileFilter());
int returnVal = fileChooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File f = fileChooser.getSelectedFile();
SomeClass c = new SomeClass(f);
c.processFile();
}
}
Although it would be better to do the processing in another thread instead of the Event dispatch thread.

In your main class you should return the file F.
That way from any other class in the same package you can call the OpenActionPerformed() method and have it returned into a new File object in whatever class you use it from.

Related

Is there any way to get the data out of Default Constructor and use it in other method?

I am trying to build a project where I will be exporting the data from h2db and store it as CSV file.
I am planning on taking the destination path for the CSV file(which is to be saved) from the user.
Class name is Export and here in default constructor swing events are happening.
I want the value of getSelectedFile(),(that is the path selected by user) to be able to use in another method.
I have created class variable - path of string type when trying to use the value all I am getting is null.
Thanks in Advance :)
Here is the code,
public class export extends JFrame{
private BufferedWriter fileWriter;
private JPanel contentPane;
private static JTextField tableName;
private JButton exportButton;
private JButton PathButton;
private String path;
private String temp;
public export() {
//Some labels and textfields
JFrame frame = new JFrame("CSV Export");
PathButton = new JButton("Destination Path");
PathButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int option = fileChooser.showOpenDialog(frame);
if(option == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
path = fileChooser.getSelectedFile().toString();
label.setText("Folder Selected: " + file.getName());
System.out.println(file.getName());
System.out.println("getCurrentDirectory(): "
+ fileChooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "
+ fileChooser.getSelectedFile());
path = fileChooser.getSelectedFile().toString();
exportButton.setEnabled(true);
}else {
label.setText("Open Command canceled");
exportButton.setEnabled(false);
}
}
});
PathButton.setFont(new Font("Tahoma",Font.PLAIN,13));
PathButton.setBounds(120,230,130,30);
contentPane.add(PathButton);
}
}

Java get selected folder path

In application im asking user to choose folder however using code below Im unable to use this input as variable path
public class csvtoxls {
public static void main() throws IOException {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
jfc.setDialogTitle("Wybierz folder do konwersji: ");
jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
jfc.setAcceptAllFileFilterUsed(false);
int returnValue = jfc.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
if (jfc.getSelectedFile().isDirectory()) {
System.out.println("You selected the directory: " + jfc.getSelectedFile());
So in order to achieve this I used function:
public class getpath {
public static String pickPath(JFileChooser fileChooser)
{
String path = null;
/* create a JFrame to be the parent of the file
* chooser open dialog if you don't do this then
* you may not see the dialog.
*/
JFrame frame = new JFrame();
frame.setAlwaysOnTop(true);
// get the return value from choosing a file
int returnVal = fileChooser.showOpenDialog(frame);
// if the return value says the user picked a file
if (returnVal == JFileChooser.APPROVE_OPTION)
path = fileChooser.getSelectedFile().getPath();
return path;
}
}
Variable:
Path workDir = Paths.get(getpath.pickPath(jfc));
The problem with this solution is that user have to choose folder twice wich can easily lead to mistake. Is there way to get this path easier?

ShowopenDialog not working under actionlistener

So I have been trying to make a filechooser that opens a text file and then paste the contents in a JtextArea I have defined as textArea.
But I cannot get my showOpenDialog to not give an error while having the argument (this), and I researched and the answer was to fill in (null) and this does make the filechooser work but when I try to print the contents of it it also just returns null. I am using the Eclipse program hence the auto filled code.
I am fairly new to Java and have no clue what is going wrong.
Im really sorry if this is not the way to post things here.
JButton btnNewButton = new JButton("Bladeren");
btnNewButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
String content = readFile(selectedFile, StandardCharsets.UTF_8);
System.out.println(content);
textArea.setText(content);
}
}
private String readFile(File selectedFile, Charset utf8) {
// TODO Auto-generated method stub
return null;
}
}
);
You can look into the API that the parameter has to be from type Component. So what does this mean in your example? Which other class/interface does your class extends from or implements?
You didn't paste the code of your readFile method but ask why it returns null? This way we cannot help you so please post the code.

Is it possible to select multiple directories at once with JFileChooser

As the title states, is there a way to select multiple directories at once (all sub-directories immediately within a primary directory) with JFileChooser so I don't have to re-open the file chooser window for each directory?
Once again I've solved my own question after asking it.
The thing that was preventing me from getting it to work previously was I was using the check for multi-select rather than the set for multi-select, and apparently was using that wrong as well as I kept getting an error. Anyway, the working version is below:
class AddDirectory implements ActionListener {
public void actionPerformed(ActionEvent ae) {
File[] theDir = null;
theDir = selectDir();
if(theDir != null) {
for(File z : theDir) {
String[] curRow = { z.toString(), "Waiting"};
dlm.addRow(curRow);
}
}
return;
}
private File[] selectDir() {
JFileChooser fileChooser = new JFileChooser(lastDir);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int showOpenDialog = fileChooser.showOpenDialog(null);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) {
return null;
}
File[] uploadDir = fileChooser.getSelectedFiles();
lastDir = new File(uploadDir[uploadDir.length-1].getParent());
return uploadDir;
}
}
Once I get the directories, they're loaded into a JTable to be modified before running the rest of my code on them.

how to open file with specific extension in fileDialogue

I am trying to Open a file with specific extension ( .fcg or .wtg ) using file Dialog
is there a way to do it ??
If you can use JFileChooser you can use JFileChooser.addChoosableFileFilter() to filter files by extension.
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileFilter() {
#Override
public String getDescription() {
return "*.fct, *.wtg";
}
#Override
public boolean accept(File f) {
return f.getName().endsWith(".fcg") ||
f.getName().endsWith(".wtg");
}
});
You can use this this code to choose a file and read
public void openFile() throws Exception {
int rowCount = 0;
int rowNo = 2;
String id = "";
String name = "";
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(new JPanel());
if (result == JFileChooser.APPROVE_OPTION) {
String file = String.valueOf(fc.getSelectedFile());
File fil = new File(file);
System.out.println("File Selected" + file);
FileInputStream fin = new FileInputStream(fil);
int ch;
while ((ch = fin.read()) != -1) {
System.out.print((char)ch);
}
} else {
}
}
As this is google search #1 for me, this is the solution which worked best for me:
How to restrict file choosers in java to specific files
specifics:
JFileChooser open = new JFileChooser(openPath);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PLSQL Files", "sql", "prc", "fnc", "pks"
, "pkb", "trg", "vw", "tps" , "tpb");
open.setFileFilter(filter);

Categories