0

I'm trying to learn GUI programing and I didn't find why and how to fix my code. my problem is that I'm using JFileChooser to open a file and when I want to cancel the option or close the JFileChooser window, it throws me this exceptions:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at myForm.OpenFile(myForm.java:296)
at myForm.openVActionPerformed(myForm.java:230)
at myForm.access$1(myForm.java:222)
at myForm$2.actionPerformed(myForm.java:102)

this is my code:

private void OpenFile() {
    try {
        File thisFile;
        JFileChooser of = new JFileChooser();
        int option = of.showOpenDialog(of);
        while (!of.getSelectedFile().getName().endsWith(".xml")) {
            String error = "Error, Please select xml file";
            JOptionPane.showMessageDialog(this, error, "Wrong type of file", JOptionPane.INFORMATION_MESSAGE);
            of = new JFileChooser();
            option = of.showOpenDialog(of);
        }
        if (option == JFileChooser.APPROVE_OPTION){
            thisFileName = of.getSelectedFile().getPath();
            thisFile =  new File(thisFileName);
            pointsList.clear();
        }
        else {
            Iterator<Point> i = pointsList.iterator();
            while(i.hasNext()) {
                p = i.next();
                drewPoints(p.x, p.y);
            }
            return;
        }
        //.... the next lines irrelevant for my question...
Gabriel
  • 121
  • 1
  • 1
  • 8
  • What's the name of the exception you are getting? And can you be sure that `getSelectedFile()` will always return a file, even if the user clicks Cancel or closes the window? – Platinum Azure Jan 23 '15 at 18:00
  • http://stackoverflow.com/questions/7769885/interruptedexception-after-cancel-file-open-dialog-1-6-0-26 I believe this will answer your question. – ShellFish Jan 23 '15 at 18:02
  • 1
    If the user presses cancel in the JFileChooser, the selected file is null. You're probably getting a NPE because you're assuming the file object returned is always valid. `getSelectedFile().getName().endsWith(".xml")`. If `getSelectedFile()` returns null, calling `getName()` on it will generate an exception. You should check the value of `of` which takes the value of a `JFileChooser` integer corresponding to what the user clicked. `JFileChooser.CANCEL_OPTION` indicates a cancel operation. – Ryan J Jan 23 '15 at 18:04
  • I editted my question and wrote the exception, getSelectedFile() will return a file when I press "open" and I tried to use the JFileChooser.CANCEL_OPTION but still didn't work – Gabriel Jan 23 '15 at 18:14

1 Answers1

0

you need to put this before the while statement.

if (option == JFileChooser.APPROVE_OPTION){

or as part of the while statement so it also stops when there is a cancel action.

David Coler
  • 453
  • 3
  • 8