I am facing this issue in another project which has complicated JPanels structure and much code.
In there I have a following snippet
Point point = label.getLocation();
Point point2 = SwingUtilities.convertPoint(label.getParent(), point, panel);
in where label and panel are selected dynamically and JLabel is supposed to be grand-grand-…-child of JPanel.
So why question is in what case SwingUtilities.convertPoint() can return negative values if source and destination have child-parent relation? Is this possible at all?
This code demonstrated negative coordinates issue, but there panel22 is not parent of label.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class NegativeLocation {
public static void main(String[] args) {
new NegativeLocation();
}
public NegativeLocation() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
JPanel panel1 = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
};
JPanel panel21 = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
};
panel1.add(panel21);
JPanel panel22 = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
};
panel1.add(panel22);
JPanel panel3 = new JPanel() {
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
};
panel21.add(panel3);
JLabel label = new JLabel("Label");
panel3.add(label);
frame.getContentPane().add(panel1);
frame.setPreferredSize(new Dimension(600, 400));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Point point = label.getLocation();
Point point2 = SwingUtilities.convertPoint(label.getParent(), point, panel21);
Point point3 = SwingUtilities.convertPoint(label.getParent(), point, panel22);
System.out.println(point2);
System.out.println(point3);
}
});
}
}
So the output is
java.awt.Point[x=134,y=10]
java.awt.Point[x=134,y=-395]
UPD: Basically, I need to get location of label relative to panel21. How can I modify this line to achive it?
Point point = label.getLocation();
Point point2 = SwingUtilities.convertPoint(label.getParent(), point, panel21);
Take the following example…
Which generates (on my system) the following output
If I pass the
labelas the source component, I get relative positions based upon the relationship between thelabeland the component whose coordinate space I’m trying to convert to. If I pass thelabel‘s parent, I’m using the parent coordinate space instead, which is bound to produce an incorrect resultIf you look at the relationship between
labelandbelowit makes sense to that you would get negative results, aslabelis above and to the right ofbelow