开发者

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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜