如何从一个动作到另一个动作获取文件的路径?

时间:2013-06-06 21:40:11

标签: java

我有点问题。我想从打开Action获取文件的路径,我想在保存操作中使用它和另外两个...对我来说最好的是保存字符串的路径,但我不知道这是怎么做的。 这是我的代码:

final String pathmain;
        Action open = new AbstractAction("Open"){
            public void actionPerformed(ActionEvent e){
                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "Pliki tekstowe txt", "txt");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(getParent());
                if(returnVal == JFileChooser.APPROVE_OPTION) {
                  // System.out.println("You chose to open this file: "+ chooser.getSelectedFile().getName());
                  String path = chooser.getSelectedFile().toString();

                  try {
                    FileReader fr = new FileReader(path);
                    BufferedReader br = new BufferedReader(fr);
                    String s;
                    while((s = br.readLine()) !=null){
                        textarea.append(s+"\n");
                    }
                } catch (FileNotFoundException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                }
            }
        };
        Action save = new AbstractAction("Save"){
            public void actionPerformed(ActionEvent e){
                try {
                    BufferedWriter out = new BufferedWriter(new FileWriter("aaa.txt"));
                    String buffer = textarea.getText();
                    //FileWriter fw = new FileWriter((textarea.getText().toString()));
                    //textarea.write(pw);
                    out.write(buffer);
                    out.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        };

1 个答案:

答案 0 :(得分:0)

将所选文件存储在定义这两个操作的对象的属性中。

public class MyPanel extends JPanel {

    private File selectedFile;

    public MyPanel() {
         Action open = new AbstractAction("Open") {
             public void actionPerformed(ActionEvent e) {
                 ...
                 selectedFile = ...
             }
         };
         ...
    } 
}