0

I want to unselect the file from JFileChooser, when i click some button. For example, if i click "Reset" button, the selected file from JFileChooser will be unselect.

Here's the code of my 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();

And here the Reset button code :

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

Thanks.

pamarnath
  • 304
  • 2
  • 3
  • 13
  • There are many problems with your code. You configure the dialog after you show it (change the order so showOpenDialog() is the last before chooser.getSelectedFile()). Your create a filter but you aren't setting it in the File Chooser. – PhoneixS Jul 01 '16 at 09:57

2 Answers2

1

You don't really want to clear the file of the JFileChooser, you reset the string you have in your class (and the representation of it, normally in a JLabel). And you should reuse the file chooser.

If you don't reset and don't recreate it each time, the user will have the same directory opened which is usually a good UX.

A simple example could be as follow:

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 = "";
  }

}

If for whatever reason you want to change the selected file in the JFileChooser see JFileChooser.showSaveDialog(...) - how to set suggested file name.

And also take a look at the official tutorial in How to Use File Choosers.


See my comments about other problems in your code.

Community
  • 1
  • 1
PhoneixS
  • 8,769
  • 4
  • 48
  • 66
1
fileChooser.setSelectedFile(new File(""));

Works for me with Java 1.6 and above.

ceklock
  • 5,596
  • 10
  • 52
  • 75