What is the difference between frame and null in showMessageDialog in Java?

Say I have a JFrame class object as a frame

I was wondering what is the difference between

JOptionPane.showMessageDialog(null,message) 

and

 JOptionPane.showMessageDialog(frame,message) 

to print something. Both give the same result, and they appear in the same place. So I was wondering what is the difference between the two? What is actually happening in the background?

+4
source share
4 answers

When you provide a frame or any other component, the options panel will appear in the middle of the component. However, if you provide zero, it will appear in the middle of the screen.

In your case, I think your Jframe has a screen size. Therefore, if you reduce the size of the frame and run it by default, then in the upper left corner you can see the difference.

+5
source
 // the dialog is centered on the desktop JOptionPane.showMessageDialog(null,message) // the dialog is centered on the frame JOptionPane.showMessageDialog(frame,message) 
+5
source

From the java documentation:

parentComponent Defines the component that should be the parent of this dialog box. It is used in two ways: the frame that contains it is used as the parent of the frame for the dialog box, and its screen coordinates are used when placing the dialog box. In general, a dialog box is located just below the component. This parameter may be zero, in which case the default frame is used as the parent, and the dialogue will be centered on the screen (depending on L and am);

Read the documentation here for more details.

+4
source

Both will do almost the same stuff.

In this example, my first argument to JOptionPane showMessageDialogmethod is a frame object (which is supposedly an instance of JFrame). If for some reason you don’t have a reference to the JFrameor JWindow instance, you can make this field null and still display the identical JOptionPane dialog.

And from the docs

parentComponent - defines the frame in which the dialog is displayed; if null or if parentComponent does not have a Frame, the default Frame is used.

The default frame is your main screen .

+2
source

Source: https://habr.com/ru/post/1498571/


All Articles