James MV
James MV

Reputation: 8717

Handling a JFileChooser window close?

I have a JFileChooser that is created as shown:

JFileChooser chooser = new JFileChooser();
int choosen = chooser.showOpenDialog(fileSelector.this);

if (choosen == JFileChooser.CANCEL_OPTION) {
  System.out.println("Closed");
}

If I close the window with out making a selection I get the error:

Exception in thread "main" java.lang.NullPointerException
    at fileSelector.fileSelector(fileSelector.java:32)
    at createAndControl.main(createAndControl.java:15)

I wanted to know what the proper way to handle this was, what action should I call on window closed to avoid this?

TIA

Upvotes: 0

Views: 3289

Answers (1)

keuleJ
keuleJ

Reputation: 3486

It's recommended to do it the other way round:

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            JFileChooser fc = new JFileChooser();
            int returnVal = fc.showOpenDialog(null);

            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                //This is where a real application would open the file.
                System.out.println("Opening: " + file.getName() + ".\n");
            } else {
                System.out.println("Open command cancelled by user.\n");
            }
        }
    });
}

Upvotes: 2

Related Questions