简体   繁体   English

在所需位置将JDialog和其JFrame父屏幕显示在同一屏幕上

[英]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. 我试图在用户单击JFrame的位置添加JDialog。 If I'm using only one screen, the following JDialog code works: 如果仅使用一个屏幕,则以下JDialog代码有效:

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? 如何获得所需的行为?

You need to convert the mouse point (from the MouseEvent ) to screen coordinates, something like MouseEvent#getLocationOnScreen should work. 您需要将鼠标点(从MouseEvent )转换为屏幕坐标,类似MouseEvent#getLocationOnScreen东西应该可以工作。

If you want to centre the dialog around the point, make sure you use pack on the dialog before using its size / preferredSize 如果要使对话框围绕该点居中,请确保在使用对话框的size / preferredSize之前在对话框上使用pack

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM