tags:

views:

606

answers:

2

I’ve always been using code similar to the following to display dialogs:

JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(this), … yada

However, I’m now thinking that this is "more correct":

JOptionPane.showMessageDialog(getRootPane(), … yada

What do people prefer / recommend?

+1  A: 

Neither one is "more correct" - it just depends on what effect you want. From the JOptionPane JavaDocs -

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).

In your case, you want the dialog to be centered on a frame - JOptionPane.getFrameForComponent(component), or SwingUtilities.getWindowAncestor(component) work from any component; getRootPane() only works from a RootPaneContainer (i.e. probably a JFrame) and you might as well just use "this" in that context.

Nate
I didn't realise SwingUtilities has that method - That may be what I want as I always want to center relative to the window containing the component that's displaying the dialog. Presumably this is slightly more generic than getRootPane() as it will handle the situation where the "containing" Window is not a root pane container.
Adamski
A: 

if you're extending JFrame or JDialog, for instance, you can use just this as the parameter:

JOptionPane.showMessageDialog(this, ...);
cd1
Unfortunately this will not do what I want: Assuming this is the Component invoking the JOptionPane.showXXX call this will center the dialog relative to the component, not the containing frame or dialog.
Adamski