首页 > 解决方案 > 使用 JFileChooser 返回路径

问题描述

好吧,我有一个返回路径的方法,通过JFileChooser,我想将该路径保存在一个变量中,然后修改一个File. JFrame但是当我用 line:调用按钮中的方法时 tf.guardarTareasHash(operator.obtenerTabla(), "modificar", tf.path());,我意识到我FileDialog再次打开以选择文件。

本来想用tf.path()send之类的参数,但没想到会再次打开JFileChooser。如果程序将保存新文件或修改,该行发送一个和修饰符是我在条件中发送用于检查operator.obtenerTabla()Hashtable一个。String

    public String path(){
        JFileChooser jfc = new JFileChooser();
        jfc.setCurrentDirectory(new 
        File("C:\\Users\\ARCANET\\Documents\\NetBeansProjects\\hash\\tareas"));
        jfc.showOpenDialog(jfc);
        String ruta = jfc.getSelectedFile().getAbsolutePath();        
        return ruta;
}

¿ 无论如何都可以在不打开文件的情况下存储所选文件的路径OpenDialog?我想static为它做一个变量。

标签: javaswingjfilechooser

解决方案


如果我理解正确你想要

tf.guardarTareasHash(operator.obtenerTabla(), "modificar", tf.path());

不要再次打开文件对话框。在这种情况下,您需要在第一次调用路径方法时存储它的结果,然后将结果作为第三个参数传递,而不是再次调用路径方法。

class MyClass {
    String myPath = null;
    ...
    // call the path method which opens the file dialog
    myPath = path();
    ...
    // use the saved result
    tf.guardarTareasHash(operator.obtenerTabla(), "modificar", myPath);
}

myPath如果未初始化,您仍然必须执行检查(例如用户取消文件对话框)


推荐阅读