Search code examples
javaswingjoptionpane

JOptionPane window opens in background


I am developing a swing application, just a little query about JOptionPane.showMessageDialog() which is bugging me:

  • JOptionPane.showMessageDialog(null, "Record entered successfully");
    If i write this code the Message window appears at the back of my parent frame.
  • JOptionPane.showMessageDialog(this, "Record entered successfully");
    whereas this code automatically places the window over the parent frame.

The question is: while implementing null as the first argument i get the message at the background of current parent frame whereas if i write this as the first argument the window comes over the parent frame. Why is this happenning?


Solution

  • In the method

    showMessageDialog(Component parentComponent, Object message)
    

    the first argument sets the parent of the dialog:

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

    I assume that the method appears inside a JFrame class, in which case passing this as the argument will set the parent component as that frame.