Java Swing: How to keep parent window open after closing JFileChooser

820 Views Asked by At

After opening a JFileChooser from a button in a window, the File Chooser opens, then the original window closes. I would like to keep that original window open throughout when the user is using the File Chooser and after.

My code:

// Code from the class that makes the original window that has the launch button
FilePicker filePicker = new FilePicker();
public void actionPerformed(ActionEvent e) {
            txtImportLog.append("\nUser selecting file");
            if (filePicker.canPick()) {
            filePicker.init();
            filePicker.getImportFile();
            } else {
                txtImportLog.append("\nCan't pick more files.");
            }
        }
    }); 

// Code from the class that creates a FilePicker 
//(yes, I know the getImportFile() and init() methods are setup badly, its just for
// testing right now
// Initialize - only should be called once
public void init() {
    filePicker = new JFileChooser();
    interval1 = 0;
    interval2 = 0;
    testFile = new File(""); // for testing. clearly.
}

// Get a file to import
public static File getImportFile() {
    filePicker.setFileSelectionMode(JFileChooser.FILES_ONLY);
    filePicker.showOpenDialog(filePicker);
    return filePicker.getSelectedFile();

}
2

There are 2 best solutions below

1
On BEST ANSWER

Oops, I simply had code (auto-generated by Eclipse plug-in WindowBuilder) that looked for when the parent window lost focus, it would close the application. The file chooser's parent was the main window. So when the user clicked the "Open file chooser" button, focus of the main window would be lost, closing the application.

0
On

Lets see setDefaultCloseOperation. http://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html

Sets the operation that will happen by default when the user initiates a "close" on this frame. You must specify one of the following choices: DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object. HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects. DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects. EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications. The value is set to HIDE_ON_CLOSE by default. Changes to the value of this property cause the firing of a property change event, with property name "defaultCloseOperation".