2016-04-07 32 views
0

我想从JFileChooser取消选择文件,当我点击一些按钮。 例如,如果我点击“重置”按钮,从JFileChooser选定的文件将被取消选择。清除选定的文件格式JFileChooser

这里是我JFileChooser代码:

public void fileChoose(){ 
    JFileChooser chooser = new JFileChooser(); 
    chooser.showOpenDialog(null); 
    chooser.setCurrentDirectory(new File(System.getProperty("user","home"))); 
    FileNameExtensionFilter filter = new FileNameExtensionFilter("jpg", "png"); 
    File file = chooser.getSelectedFile(); 
    String path = file.getAbsolutePath(); 

而且这里的Reset按钮代码:

private void clearAllField(){ 
    nik_input.setText(""); 
    name_input.setText(""); 
    born_input.setText(""); 
    birth_date_input.setDate(null); 
    gender_input.setSelectedIndex(0); 
    address_input.setText(""); 
    job_input.setText(""); 

感谢。

+0

你的代码有很多问题。在显示它之后配置对话框(更改顺序,以便showOpenDialog()是chooser.getSelectedFile()之前的最后一个)。你创建一个过滤器,但是你没有在File Chooser中设置它。 – PhoneixS

回答

1

你并不是真的想要清除JFileChooser的文件,你重置了你在类中的字符串(以及它的表示,通常是在JLabel中)。你应该重用文件选择器。

如果您不重置并且每次都不重新创建,那么用户将会打开相同的目录,这通常是一个很好的UX。

一个简单的例子可以如下:

public class Foo { 

    JFileChooser chooser; 
    String path; 

    public Foo() { 
    this.chooser = new JFileChooser(); 
    chooser.setCurrentDirectory(new File(System.getProperty("user","home"))); 
    // TODO Other file chooser configuration... 
    path = ""; 
    } 

    public void fileChoose(){ 

    chooser.showOpenDialog(null); 
    File file = chooser.getSelectedFile(); 
    this.path = file.getAbsolutePath(); 

    } 

    public String getPath() { 
    return this.path; 
    } 

    public String resetPath() { 
    this.path = ""; 
    } 

} 

如果因任何原因要更改JFileChooser中选定的文件中看到JFileChooser.showSaveDialog(...) - how to set suggested file name

还可以看看官方教程How to Use File Choosers


看到我的意见,关于您的代码中的其他问题。