JFileChooser没有出现

时间:2013-02-01 05:07:53

标签: java swing user-interface jfilechooser

我有一个方法,它以txt个文件作为输入。我曾经通过键入文件的直接路径来使用字符串。 但每当我尝试使用不同的文件进行输入时,它就会变得很麻烦。我尝试实施JFileChooser,但没有运气。

这是代码,但没有发生任何事情。

public static JFileChooser choose;
File directory = new File("B:\\");
choose = new JFileChooser(directory);
choose.setVisible(true);        
File openFile = choose.getSelectedFile();

FileReader fR = new FileReader(openFile);
BufferedReader br = new BufferedReader(fR);

4 个答案:

答案 0 :(得分:7)

根据How to Use File Choosers上的Java教程:

  

打开标准的打开对话框只需要两行代码:

//Create a file chooser
final JFileChooser fc = new JFileChooser();
...
//In response to a button click:
int returnVal = fc.showOpenDialog(aComponent);
  

showOpenDialog方法的参数指定父级   对话框的组件。父组件影响其位置   对话框和对话框所依赖的框架。

注意as per docs它也可以是:

int returnVal = fc.showOpenDialog(null);
  

如果父级为null,则对话框取决于没有可见窗口,   并且它被放置在依赖于外观和感觉的位置,例如   屏幕中心。

如果您还没有,请在Concurrency in Swing上阅读。

答案 1 :(得分:2)

没有阻止代码(正如David Kroukamp建议的那样)。它解决了#34;没有出现"问题

Runnable r = new Runnable() {

@Override
public void run() {
    JFileChooser jfc = new JFileChooser();
    jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    if( jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION ){
        selected = jfc.getSelectedFile();
    }
}
}
SwingUtilities.invokeLater(r);

答案 2 :(得分:1)

对于JFileChoosers,您应该致电objectName.showOpenDialog(Component parent)objectName.showOpenDialog(Component parent)。这些方法将返回一个整数,您可以使用该整数与JFileChooser中设置的静态常量进行比较,以确定用户是单击取消还是打开/保存。然后使用getSelectedFile()检索用户选择的文件。

Ex(可能存在小错误):

class Example {
    public static void main(String[] args) {
        JFileChooser jfc = new JFileChooser();
        File selected;

        if (jfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            selected = jfc.getSelectedFile();
        }
    }
}

Java API是一个很好的资源,用于确定哪些对象可以做什么,以及如何做。这是JFileChoosers

的页面

当您使用Google对象名称时,通常会找到API页面。它们通常也是第一批出现的结果。

答案 3 :(得分:0)

我个人发现第一个对话框将显示,但随后的对话框将不显示。我通过使用此代码重复使用相同的JFileChooser来解决了该问题。

JFileChooser jfc = new JFileChooser();
File jar = selectFile(jfc, "Select jar to append to");
File append = selectFile(jfc, "Select file to append");

//When done, remove the window
jfc.setVisible(false);

public static File selectFile(JFileChooser jfc, String msg) {
    if (!jfc.isVisible()) {
        jfc.setVisible(true);
        jfc.requestFocus();
    }

    int returncode = jfc.showDialog(null, msg);
    if (returncode == JFileChooser.APPROVE_OPTION) return jfc.getSelectedFile();
    return null;
}