ferrerverck
ferrerverck

Reputation: 618

java JFrame getLocationOnScreen returns wrong result? @ Ubuntu

I need to get JFrame location to save application position. But the problem is getLocationOnScreen() returns incorrect result. Or at least it seems so.

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);
        }
    });
}

In my opinion the code above must yield (100, 100), but instead it prints "java.awt.Point[x=101,y=128]".

How can I get the correct (100, 100) result?

UPD: Also sometimes I get (100, 100) or (101, 128). And I really can't understand the logic of it.

UPD: Two different runs of this code. enter image description here

Upvotes: 3

Views: 1103

Answers (1)

porfiriopartida
porfiriopartida

Reputation: 1556

setLocation moves to the x,y based on the parent, getLocationOnScreen will get location based on screen...

There is no guarantee that getLocation and getLocationOnScreen would be the same.. getLocation is "relative" while getLocationOnScreen is absolute.

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)

This is my output for your code:

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

Which java version are you using? Mine is 1.7.0_25, maybe there is a difference between default behaviors for JFrame since the top component "should" have as parent the screen.

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

Sometimes you get 100,100 and sometimes 101, 128

Different behaviors for JFrame.setLocation JFrame.getLocationOnScreen In windows I always get 100, 100 for this particular case.

Upvotes: 3

Related Questions