1

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

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();
                }
            }
        };
4

1 回答 1

0

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

public class MyPanel extends JPanel {

    private File selectedFile;

    public MyPanel() {
         Action open = new AbstractAction("Open") {
             public void actionPerformed(ActionEvent e) {
                 ...
                 selectedFile = ...
             }
         };
         ...
    } 
}
于 2013-06-06T21:46:21.523 回答