gpt4 book ai didi

java JFrame getLocationOnScreen 返回错误结果? @Ubuntu

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:50:46 27 4
gpt4 key购买 nike

我需要获取 JFrame 位置以保存应用程序位置。但问题是 getLocationOnScreen() 返回不正确的结果。或者至少看起来是这样。

public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setMinimumSize(new Dimension(200, 200));
frame.setVisible(true);

frame.setLocation(100, 100);

frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Point point = frame.getLocationOnScreen();
System.out.println(point);
}
});
}

在我看来,上面的代码必须产生 (100, 100),但它会打印“java.awt.Point[x=101,y=128]”。

如何获得正确的 (100, 100) 结果?

UPD:有时我也会得到 (100, 100) 或 (101, 128)。我真的无法理解其中的逻辑。

UPD:此代码的两次不同运行。 enter image description here

最佳答案

setLocation 移动到基于父级的 x,y,getLocationOnScreen 将基于屏幕获取位置...

无法保证 getLocation 和 getLocationOnScreen 相同。getLocation 是“相对的”,而 getLocationOnScreen 是绝对的。

http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#getLocationOnScreen() http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#getLocation() http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#setLocation(int , 整数)

这是我的代码输出:

java.awt.Point[x=100,y=100]

您使用的是哪个 Java 版本?我的是 1.7.0_25,JFrame 的默认行为可能有所不同,因为顶部组件“应该”将屏幕作为父组件。

Update from comments:
java version "1.7.0_25" Java(TM) SE Runtime Environment (build 1.7.0_25-b15) Java HotSpot(TM) Server VM (build 23.25-b01, mixed mode) Ubuntu 12.04

有时你会得到 100,100,有时会得到 101、128

JFrame.setLocation JFrame.getLocationOnScreen 的不同行为在 Windows 中,对于这种特殊情况,我总是得到 100、100。

关于java JFrame getLocationOnScreen 返回错误结果? @Ubuntu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19071359/

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