Mihajel Petrovic
Mihajel Petrovic

Reputation: 93

java - JFileChooser - open/cancel/exit button

I made a button that will create a JFileChooser so the user can open a .txt file, here's the code inside the action listener of the button:

JFileChooser fc = new JFileChooser();
    //filter-show only .txt files
    FileNameExtensionFilter txtfilter = new FileNameExtensionFilter("txt files (*.txt)", "txt");

    //apply the filter to file chooser
    fc.setFileFilter(txtfilter);
    fc.setDialogTitle("Otvori txt file");
    //disable the ability to show files of all extensions
    fc.setAcceptAllFileFilterUsed(false);
    //create file chooser via jFrame
    fc.showOpenDialog(jFrame);
    //get selected file
    File selFile = fc.getSelectedFile();
    Path path = Paths.get(selFile.toString());
    asdf = selFile.toString();
    //display chosen file on jLabel5
    jLabel5.setText(path.getFileName().toString());

It works just fine, if you select the .txt file inside the file chooser, but it also works if you just select a file and then press cancel and exit. I assume it's because of the getSelectedFile() but I am wondering if there is a way to make sure the user selected a file and pressed open inside file chooser as a condition to get a file?

Upvotes: 0

Views: 6942

Answers (1)

bowmore
bowmore

Reputation: 11280

You should check whether the return value from:

fc.showOpenDialog(jFrame) == JFileChooser.APPROVE_OPTION

That return value indicates how the user exited the dialog.

See JFileChooser.showOpenDialog(Component) docs.

Upvotes: 8

Related Questions