Search code examples
javaswingjdialog

Attempting to place JDIalog on top of current position of a JFrame


I'm writing an extension to a Java application; its API does not have access to the position of the main window of the application. I create my own JFrame, and it positions that JFrame with

AwtUtil.centerWindow(jFrameReference);

I would like to position the JFrame on top of the current position of the main window, but without any reference to the main window, I'm assuming I cannot do that. The above call appears to put the JFrame in the center of the #1 display on my Windows 10 machine.

But I also create a JDialog to be popped up with a button, and I would like to position that on top of my own JFrame, wherever it is when the button is clicked. To do this, I put a reference to the JFrame in the constructor for the dialog, and then in the dialog constructor call:

super(jFrameReference, title, Dialog.ModalityType.APPLICATION_MODEL);

But if I move the JFrame, then click the button to pop up the dialog, the dialog appears where the JFrame first appeared, not where the JFrame is when the button is clicked. Is the position of the JFrame somehow saved when the dialog is created (which is before it is displayed)? What am I missing here?


Solution

  • This is not a general answer, but it fixed my problem. My JDialog was created without being made visible when the JFrame was in its original position. I guess the position of the JFrame is somehow saved somewhere and used when the JDialog is displayed. I fixed the problem by storing a reference to the JFrame as a private variable in the dialog, then calling jDialogReference.setLocationRelativeTo(jFrameReference) at the time the dialog is made visible.