Szala Szala - 5 months ago 21
Java Question

Java: What is the difference beetwen getLocation() and getLocationOnScreen() at JFrame?

What is the difference beetwen

getLocation()
and
getLocationOnScreen()
metholds at
JFrame
?

I wanted to test what is the difference with this code, but the result is the same. Which method should I use?

public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(150, 100);
frame.setVisible(true);

System.out.println("getLocation: " + frame.getLocation().getX() + " " + frame.getLocation().getY());
System.out.println("getLocationOnScreen: " + frame.getLocationOnScreen().getX() + " " + frame.getLocationOnScreen().getY());
}


Output:

getLocation: 150.0 100.0

getLocationOnScreen: 150.0 100.0

Answer

When you create a JFrame like this, the parent is null, so it's the screen. That's why here, the functions returns the same values : getLocationOnScreen() returns the position of your frame relatively to your screen and getLocation() returns the position of your frame relatively to its parent, here, the screen

Comments