Center JDialog over parent(将 JDialog 居中于父级之上)
问题描述
我有一个带有按钮的 Java swing 应用程序,当执行某个操作时,该按钮会生成一个弹出窗口.我想在渲染时将弹出窗口的中心点与父窗口的中心点对齐.如何计算 x,y 坐标以插入 setLocation()
的弹出窗口?
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 居中于父级之上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 JDialog 居中于父级之上


基础教程推荐
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01