windowClosing not called in JFileChooser && System.exit not functioning properly?

54 Views Asked by At

Background

So I've been trying to improve my code style and write a bit more functionally. I write software daily not as a requirement for my job (web design), but to expedite my responsibilities and automate them and save time (this approach has proven invaluable and made me somewhat of a superstar).

Issue

In one of my recent projects, I have tried to use a JFileChooser in the following way:

List<String> lines;
    do {
        lines = new ArrayList<>();
        try {
            lines = jFC.showOpenDialog(new JFrame() {
                {
                    // originally setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    addWindowListener(new WindowAdapter() {
                        public void windowClosing(WindowEvent e) {
                            System.exit(0);
                        }
                    });
                }
            }) == JFileChooser.APPROVE_OPTION
                    ? Files.readAllLines(jFC.getSelectedFile().toPath())
                    : null;
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Error selecting File.");
        }
        System.out.println("Here we go");
    } while (lines == null || lines.isEmpty());

However neither my original implementation nor my revised one actually work, which I tested using print statements (The reimplemented version was never called.) I then tried to do the following:

JFrame test = new JFrame();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
lines = jFC.showOpenDialog(test) == JFileChooser.APPROVE_OPTION
        ? Files.readAllLines(jFC.getSelectedFile().toPath())
        : null;

Which produced the same result. I've searched for duplicates but could not find something that reproduced my exact situation. Essentially, I want my program to completely terminate anytime a JFileChooser is canceled but I am reluctant to change my ternary statements as it does not fix my intended behavior but instead proposes a work around. My intuition tells me its a scope problem but for windowClosing not to be called raises a few questions for me.

tl;dr

System.exit(0) on JFrame for JFileChooser not working, not going to change flow control so don't bother asking.

0

There are 0 best solutions below