Search code examples
javaswingjframejdialogmultiple-monitors

Show JDialog in the same screen as its JFrame parent at the desired location


I'm trying to add a JDialog at the location the user clicked on the JFrame. If I'm using only one screen, the following JDialog code works:

public class PopupCanevas extends JDialog {

    public PopupCanevas(JFrame frame, Point position) {
        super(frame);
        this.setLocation(position);
    }
}

However, if I'm using a dual monitor configuration, I'm not able to show the dialog on the screen where is my frame at the position the user clicked at. The above code will show the dialog at the desired position, but on my main screen, no matter what screen my frame is positioned at. I tried the following:

this.setLocation(frame.getLocation(position));

It will show the dialog on the correct screen, but on the top left corner and not at the desired position.

How can I get the desired behavior?


Solution

  • You need to convert the mouse point (from the MouseEvent) to screen coordinates, something like MouseEvent#getLocationOnScreen should work.

    If you want to centre the dialog around the point, make sure you use pack on the dialog before using its size/preferredSize