Susanna Ferrari
Susanna Ferrari

Reputation: 11

JFileChooser for passing selected file into argument of different class object

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!

Upvotes: 0

Views: 1631

Answers (2)

Set of Theseus
Set of Theseus

Reputation: 377

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.

Upvotes: 0

Swaranga Sarma
Swaranga Sarma

Reputation: 13413

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.

Upvotes: 1

Related Questions