清除选定的文件格式JFileChooser

问题描述 投票:0回答:2

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

谢谢。

java jfilechooser
2个回答
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的官方教程。


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


0
投票
fileChooser.setSelectedFile(new File(""));

适用于Java 1.6及以上版本。

© www.soinside.com 2019 - 2024. All rights reserved.