Search code examples
javacomponentsparentjfilechooser

What is parent Component for in JFolderChooser.showOpenDialog


Case 1:

JFileChooser myFileChooser;
myFileChooser.showOpenDialog(this); //this = parent Component

Case 2:

JFileChooser myFileChooser;
myFileChooser.showOpenDialog(null);

What is the practical difference between the two cases?


Solution

  • Checkout the Javadoc for JFileChooser

    The parent argument determines two things: the frame on which the open dialog depends and the component whose position the look and feel should consider when placing the dialog. If the parent is a Frame object (such as a JFrame) then the dialog depends on the frame and the look and feel positions the dialog relative to the frame (for example, centered over the frame). If the parent is a component, then the dialog depends on the frame containing the component, and is positioned relative to the component (for example, centered over the component). If the parent is null, then the dialog depends on no visible window, and it's placed in a look-and-feel-dependent position such as the center of the screen.

    internally it tries to get a window using the parent using this JOptionPane.getWindowForComponent(parent). Which in turn checks if parent is null or not...

    if (parentComponent == null)
        return getRootFrame();
    

    If it is null then Root level frame is returned as parent container. Using the internal SwingUtilities.getSharedOwnerFrame(). The javadoc for SwingUtilities.getSharedOwnerFrame() says...

    Returns a toolkit-private, shared, invisible Frame to be the owner for JDialogs and JWindows created with null owners.