Question

Maybe this is a stupid question but I lose hours trying it. I have any JFrame with her components inside. This JFrame can have any Layout. My question is simple I have this window: In the image I use absolute layout to know the real location.

enter image description here

I want know the position of the button. I'm using a GridBagLayout and when I do button.getY() or button.getX() , I have 0 ever, in X or Y. But if I use absolute layout, I have not problem.

If I use absoluteLayout I know that I have not this problem. But I want use any layout and know the absolute position of any component in the frame.

Really I want to do a autocomplete textField ( like google when you are writing to search ), when I write in the TextField , I want show other window jframe below textfield with the coincidences.

If I know the absolute position of any textfiel, I can calculate the position and show the new window.

Thanks to all.

Was it helpful?

Solution

One of the SwingUtilities.convertPoint() methods should do what you want. The following example prints java.awt.Point[x=54,y=22].

image

JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JLabel("Test"), BorderLayout.WEST);
JButton b = new JButton("Test");
f.add(b);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
System.out.println(SwingUtilities.convertPoint(b, b.getX(), b.getY(), f));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top