简体   繁体   中英

Getting coordinates of a JTextField in a JFrame

I've added a JTextField in a JFrame using the BorderLayout .
Now I want to know the location of the JTextField .

I used getX() and getLocation() , but both gives me 0 , which is not the right answer.
So how do I get that location?

The getLocation() method gives the location of the component relative to its parent in this case the content pane, so the location may in fact be 0. Also you can't invoke the method until the frame is visible.

If you want the location relative to the frame then you need to use

SwingUtilities.convertPoint(...);

Calling getLocation() in a component (the JTextField ) should return its coordinates relative to the parent container (in the example below, the JFrame ).

Note : You will have to do the layout in the container ( JFrame ) before getting the coordinates.
Doing the layout is acomplished by simply showing it.

Example :

JFrame fr = new JFrame("Testing window");
JTextField tf = new JTextField();
fr.add(tf, BorderLayout.CENTER);

fr.setVisible(true); //show the JFrame

Point p = tf.getLocation(); //get the coordinates

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM