中心JDialog超过父级 [英] Center JDialog over parent

查看:98
本文介绍了中心JDialog超过父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有按钮的Java swing应用程序,当执行某个操作时会生成一个弹出窗口。我想在弹出窗口的中心点与渲染时父窗口的中心点对齐。如何为弹出窗口计算插入 setLocation()的x,y坐标?

I have a Java swing application with a button that produces a popup window when a certain action is performed. I'd like to align the center point of the popup window with the center point of the parent window when it is rendered. How can I calculate the x,y coordinates to plug into setLocation() for the popup window?

澄清。我不希望 setLocationRelativeTo()的行为,因为它将弹出窗口的左上角像素设置在父框架的中心像素上。我想将弹出窗口的中心像素设置在父帧的中心像素上。

Just to clarify. I do not want the behavior of setLocationRelativeTo() because that sets the top-left pixel of the popup over the center pixel of the parent frame. I want to set the center pixel of the popup over the center pixel of the parent frame.

推荐答案


setLocationRelativeTo ..这套弹出窗口的左上角像素位于父级的中心像素上方。 ..

setLocationRelativeTo ..this sets the top left pixel of the popup over the center pixel of the parent. ..

不,不是!

此简单示例弹出的3个对话框中的每一个都显示为我可以看到我的中心。我只能猜测代码在错误的时间调用 setLocationRelativeTo

Each of the 3 dialogs popped by this simple example appears to be centered as far as I can see. I can only guess that the code is calling setLocationRelativeTo at the wrong time.

import javax.swing.*;

class CenterTheDialog {

    CenterTheDialog() {
        for (int ii=1; ii<4; ii++) {
            JFrame f = new JFrame("Frame " + ii);
            f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

            f.setSize(400,300);
            f.setLocationByPlatform(true);
            f.setVisible(true);

            JDialog d = new JDialog(f);
            d.setSize(300,200);
            d.setLocationRelativeTo(f);
            d.setVisible(true);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new CenterTheDialog();
        });
    }
}

这篇关于中心JDialog超过父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆