I use Jave Swing and the simplified hierarchy can be understood as JFrame -> JPanel -> JLabel.
Now I have options of adding JLabel into JPanel:
- panel.add(label);
- panel.setLayout(new BorderLayout()); panel.add(label, BorderLayout.NORTH);
This is common configuration I am doing in both cases
panel.setOpaque(false);
panel.setBorder(BorderFactory.createLineBorder(Color.yellow));
Even though I keep all other code unchanged the following method call gives very different results:
Point location = getLocationOnFrame(label);
I call this method to identify location of JLabel relative to JFrame:
public Point getLocationOnFrame (JLabel label) {
if (label == null) return null;
try {
Point location = label.getLocationOnScreen();
System.out.println(location);
Point frameOffset = mainFrame.getLocationOnScreen();
System.out.println(frameOffset);
location.translate(-frameOffset.x, -frameOffset.y);
return location;
} catch (IllegalComponentStateException e) {}
return null;
}
These are results from System.out.println() even though visiually the label appears in the same place.
java.awt.Point[x=578,y=305]
java.awt.Point[x=0,y=0]
java.awt.Point[x=224,y=300]
java.awt.Point[x=0,y=0]
It seems to me that in 2nd case the numbers come from the left-top corner of parent JPanel not JLabel itself.
Basically I am trying to use the code from 2nd case and get numbers from 1st.
As to why you’re getting different results, I have absolutely no idea.
However, I believe you’re making more work for your self…
Will convert the labels coordinates to the windows coordinate space for you.
Know remember, the location of the frame is the top left corner of the frame (no, really it is ;)), but your label exists within the frame’s
contentPanewhich is offset within the frames border, so depending on what you are trying to do, you may be better using thecontentPaneinstead of the frame 😉This is a simple example I used to test the logic 😉