gpt4 book ai didi

java - 使用双屏时显示 JFrame 在主显示器居中

转载 作者:行者123 更新时间:2023-12-02 05:54:27 25 4
gpt4 key购买 nike

我正在尝试使用 Java 编写一些代码,将我的主应用程序 JFrame 置于计算机屏幕的中心。为此,我使用下面的代码,该代码将过程分为两部分,这只是因为我在类的其他位置使用 ScreenHeight 和 ScreenWidth 进行缩放,并且它们是类的属性。

这段代码在我的笔记本电脑和其他单屏机器上完美运行,但在我的双显示器主机上,它将屏幕放置在工作区的中心,其中放置了一半的对话框(可能很小)在每个屏幕上。它位于一个方法中,以便每次程序更改对话框大小时我都可以调用它。

我使用 boolean 宽度值将屏幕保持在垂直轴上的同一位置,但使其在水平轴上居中。

// Finds the size of the screen
private void find_ScreenSize() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension dim = toolkit.getScreenSize();
ScreenHeight = dim.height;
ScreenWidth = dim.width;
}

// Centres the dialogue box within the screen
private void centre_Frame(JFrame Frame, boolean Width) {
find_ScreenSize();

if (!Width) { // if you are not justifying on the X axis
Frame.setLocation(Frame.getLocationOnScreen().x,
((ScreenWidth / 2) - (Frame.getWidth() / 2)));
} else {
Frame.setLocation(((ScreenWidth / 2) - (Frame.getWidth() / 2)),
((ScreenHeight / 2) - (Frame.getHeight() / 2)));
}
}

我希望能够将对话框置于任何多屏幕计算机上主/第一个屏幕的中心。我的应用程序中的对话框(我无法控制其位置)能够完成我想做的事情,例如我的 JOptionPane 以及文件打开和保存对话框都可以完美运行。

我正在 Linux 上进行开发,但该应用程序可在 Linux 和 MS 平台上使用。

搜索这个问题给了我很多上面的例子,但没有任何东西告诉我如何做我想做的事,任何帮助将不胜感激。

预先感谢您的帮助。

最佳答案

frame.setLocationRelativeTo(null);

应该可以工作( doc )。至少在我的多显示器设置上是这样。请注意,即使应用程序是从辅助显示器启动的,窗口也始终显示在主显示器的中心。

您可以使用GraphicsEnvironment.getCenterPoint找到中心点而不是自己计算。

如果您想在特定显示器中显示,请参阅Show JFrame in a specific screen in dual monitor configuration

关于java - 使用双屏时显示 JFrame 在主显示器居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10691094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com