Search code examples
javajfilechooserjmenuitem

java JMenuItem JFileChooser


apologies in advance if this is a stupid question but I've created a window with a menubar and two menuitems....when i click on open i want to use JFileChooser to select a file from my computer but there's an unhandled exception type file not found error on my Scanner input

public void actionPerformed(ActionEvent e) {
    JFileChooser chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("text files", "txt");
    chooser.setFileFilter(filter);
    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        //get the selected file
        java.io.File file = chooser.getSelectedFile();
        //create scanner for the file
        Scanner input = new Scanner(file);
        //read text from file
        while (input.hasNext()) {
            System.out.println(input.nextLine());
        }
        //close the file
        input.close();
    } else {
        System.out.println("No file selected");
    }
}

I know i should enter a throws Exception but none of my methods will take it....My main method throws an IOException already. Thanks in advance


Solution

  • If you don't want to throw an exception, you will need to surround the code which generates it in a try-catch block, and handle the exception locally like this:

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            //get the selected file
            java.io.File file = chooser.getSelectedFile();
            try {
                //create scanner for the file
                Scanner input = new Scanner(file);
                //read text from file
                while (input.hasNext()) {
                    System.out.println(input.nextLine());
                }
                //close the file
                input.close();
            } catch (FileNotFoundException fnfe) {
                // handle exception here, e.g. error message to the user
            }
        } else {
            System.out.println("No file selected");
        }