0

Currently I am using Netbeans. I have added a jFileChooser in a jFrame. All is ok, but when I select a file and click on the Open button of the jFileChooser it happens nothings. I want to get the selected file's address path when the button is clicked. How can I write code for the button?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Tushar Monirul
  • 4,944
  • 9
  • 39
  • 49
  • 1
    Show us the code to help you better? – Smit May 23 '13 at 15:21
  • here is the code. `private void addfileActionPerformed(java.awt.event.ActionEvent evt) { FileChooser fc = new FileChooser(); fc.setVisible(true); }` @Smit – Tushar Monirul May 23 '13 at 15:26
  • 3
    Did you read the Swing tutorial on [How to Use File Choosers](http://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html) for a working example? – camickr May 23 '13 at 15:27
  • Can you please edit your post, that would be helpful – akki0996 May 23 '13 at 15:29
  • 1
    @Tushar Please add those code to your question. Code as comment is unreadable. Moreover I never seen `addfileActionPerformed` method. Are you creating your own method? Give us the code where we can replicate the problem. We all can keep of guessing but that wont be fruitful. Also follow link given by @ camickr.. – Smit May 23 '13 at 15:37
  • Please edit your question to include an [sscce](http://sscce.org/) if you continue to have problems. – trashgod May 23 '13 at 17:53

3 Answers3

1

You could try something like this when the listener of the button is activated:

String filePath = myFileChooser.getSelectedFile().getAbsolutePath();

Of course, you may not want to store it in a String, but hey, just an example.

aran
  • 10,978
  • 5
  • 39
  • 69
1

Check the chooser's return value. If it's the APPROVE_OPTION, getSelectedFile() will return the selected File. This complete example follows API almost verbatim in ImageOpenAction.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • But i can't get the open button clicked. When I'm trying to add action performed for open button, the whole frame is selected. – Avinash Raj Sep 19 '15 at 13:07
  • @AvinashRaj: try the [example](http://stackoverflow.com/a/5129757/230513) and open a new question if you still have problems. – trashgod Sep 19 '15 at 13:38
0

If you added the JFileChooser control to your JFrame, you should not instantiate another JFileChooser. Just add two lines:

JFileChooser chooser = (JFileChooser) evt.getSource();

and the line that Asier Aranbarri gave in his answer and use your variable name (e.g. chooser) instead of myFileChooser.

By the way, if you want to know whether the Open or the Cancel button was pressed get the event command:

String command = evt.getCommand();

The string will either contain "ApproveSelection" (Open button) or "CancelSelection" (Close button).

carloabelli
  • 4,289
  • 3
  • 43
  • 70