Java JFrame的getLocationOnScreen方法返回错误结果? @ Ubuntu

3

我需要获取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) 结果呢?更新:有时候我会得到 (100, 100) 或者 (101, 128) 结果。我真的无法理解其中的逻辑。更新:此代码运行的两个不同结果如下图所示。 enter image description here

setLocation 根据父组件移动到 x、y 位置,getLocationOnScreen 将根据屏幕获取位置... 但是... 在运行您的代码后,我确实看到了 100,100。您使用的是哪个 Java 版本? - porfiriopartida
Java版本“1.7.0_25” Java(TM) SE Runtime Environment(构建1.7.0_25-b15) Java HotSpot(TM) Server VM(构建23.25-b01,混合模式)Ubuntu 12.04 - ferrerverck
有趣,我正在使用相同的Java版本,但在Windows上。似乎在Ubuntu中JFrame不是无父窗口? - porfiriopartida
是的,数字1和28看起来有点像X窗口系统框架尺寸。 - ferrerverck
很可能 getLocation 被委托给了内容窗格,它考虑了框架边框占用的额外空间。 - MadProgrammer
显示剩余2条评论
1个回答

3

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, 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。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接