清除选定的文件格式JFileChooser

时间:2016-04-07 09:56:31

标签: java 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();

这里有重置按钮代码:

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("");

感谢。

2 个答案:

答案 0 :(得分:1)

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

如果你没有重置并且每次都不重新创建它,那么用户将打开相同的目录,这通常是一个很好的用户体验。

一个简单的例子如下:

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中的官方教程。

请参阅我对您代码中其他问题的评论。

答案 1 :(得分:0)

fileChooser.setSelectedFile(new File(""));

适用于Java 1.6及更高版本。

相关问题