Java 从JFileChooser清除所选文件

Java 从JFileChooser清除所选文件,java,swing,jfilechooser,Java,Swing,Jfilechooser,单击某个按钮时,我想从JFileChooser中取消选择文件。 例如,如果我单击“重置”按钮,则从JFileChooser中选择的文件将被取消选择 这是我的JFileChooser的代码: public void fileChoose(){ JFileChooser chooser = new JFileChooser(); chooser.showOpenDialog(null); chooser.setCurrentDirectory(new File(System

单击某个按钮时,我想从
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("");

谢谢。

如果您真的不想清除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的文件,请重置类中的字符串(以及它的表示形式,通常在JLabel中)。您应该重用文件选择器

fileChooser.setSelectedFile(new File(""));
如果每次都不重置和重新创建,用户将打开同一个目录,这通常是一个好的用户体验

一个简单的例子如下:

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中更改所选文件,请参阅

还可以看一下中的官方教程


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

fileChooser.setSelectedFile(new File(""));
适用于我的Java1.6及以上版本


适用于Java 1.6及以上版本。

您的代码存在许多问题。您可以在显示对话框后对其进行配置(更改顺序,使showOpenDialog()成为chooser.getSelectedFile()之前的最后一个)。您创建了一个过滤器,但没有在文件选择器中设置。您的代码有很多问题。您可以在显示对话框后对其进行配置(更改顺序,使showOpenDialog()成为chooser.getSelectedFile()之前的最后一个)。您可以创建一个过滤器,但没有在文件选择器中设置它。