-1

File chooser UI implemented using jfilechooser in JAVA SWING

On clicking the open button, I am trying to fetch the path of the file, including the file name I opened.

Code:

private void jFileChooser1ActionPerformed(java.awt.event.ActionEvent evt) {   
    JFileChooser chooser=new JFileChooser();
    String path=chooser.getSelectedFile().getAbsolutePath();//error
    System.out.println(path);
}    

But I am getting a null pointer exception in the commented (//errror) line.

Where am I going wrong?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
vikky 2405
  • 289
  • 2
  • 11
  • 3
    Before the chooser is displayed to the user, it won't ***have*** a selected file (unless set by the programmer)! – Andrew Thompson Mar 15 '17 at 08:38
  • read the javadocs `int returnVal = chooser.showOpenDialog(parent); if(returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); }` – Scary Wombat Mar 15 '17 at 08:39
  • 1
    Instead of creating a new `JFileChooser` instance, you need to get the selected file from the event. – Filburt Mar 15 '17 at 08:40
  • @AndrewThompson so what is the order of doing this? Kindly suggest me on this, I am jsut migrating from python to JAVA – vikky 2405 Mar 15 '17 at 08:40
  • Can't speak for Python, but for Java there's this marvellous resource that can be found with a search string of 'hot to X' where in this case X is 'jfilechooser'. Top hit is [How to Use File Choosers](https://docs.oracle.com/javase/tutorial/uiswing/components/filechooser.html). Book mark the tutorial. – Andrew Thompson Mar 15 '17 at 08:50
  • @AndrewThompson thank you. – vikky 2405 Mar 15 '17 at 08:55
  • BTW - that should have been '**how** to X'.. :P But I'm hoping you figured that out. ;) – Andrew Thompson Mar 15 '17 at 08:59

1 Answers1

0

You should open it at first!

Use this sample code:

JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " + selectedFile.getAbsolutePath());
}