Search code examples
javaswingwindowjoptionpanelook-and-feel

How to get the default Frame to use as parent component?


As in a JOptionPane I want to set a parent Component when sending a null value as the component parent.

parentComponent: Defines the Component that is to be the parent of this dialog box. It is used in two ways: the Frame that contains it is used as the Frame parent for the dialog box, and its screen coordinates are used in the placement of the dialog box. In general, the dialog box is placed just below the component. This parameter may be null, in which case a default Frame is used as the parent, and the dialog will be centered on the screen (depending on the L&F).

That's how a JOptionPane works, now I want to do the same, but don't know how to get the default frame and set it as the parent to show a Notification. I'm using the NotificationManager to show a notification that is included in WebLaF L&F, but when i try to show a notification before setVisible the Frame it throws me this error

"There is no visible windows to display notification"

It comes from here:NotificationManager class:method to get the window when sending a null component as parent

private static Window getDefaulShowForWindow ()
{
    final Window activeWindow = SwingUtils.getActiveWindow ();
    if ( activeWindow != null )
    {
        return activeWindow;
    }
    final Window[] allWindows = Window.getWindows ();
    if ( allWindows != null && allWindows.length > 0 )
    {
        return allWindows[ 0 ];
    }
    throw new RuntimeException ( "There is no visible windows to display notification" );
}

SwingUtils class: method getActiveWindow()

public static Window getActiveWindow ()
{
    final Window[] windows = Window.getWindows ();
    Window window = null;
    for ( final Window w : windows )
    {
        if ( w.isVisible () && w.isActive () && w.isFocused () )
        {
            window = w;
            break;
        }
    }
    return window;
}

So what I want to know is what does JOptionPane do(in code) when sending a null Component as parent.


Solution

  • If you have a look at JOptionPane, it will eventually end up in showOptionDialog(Component, Object, String, int, int, Icon, Object[], Object)

    In this method, when parentComponent is null, it calls getRootFrame. This does some interesting work. Basically it works with SwingUtilities to "find" a suitable Frame to use. If one doesn't exist, it will frame a "shared" reference...

    This is generated via SwingUtilities.getSharedOwnerFrame, which will (eventually) create a Frame called SharedOwnerFrame, which has overriden the show method so that it can never be displayed...

    This is all done from within a package-private level, so you can't call any of this functionality yourself...

    Updated

    I should point out that the same instance of SharedOwnerFrame is used by all JOptionPanes