简体   繁体   English

在JFrame中获取JTextField的坐标

[英]Getting coordinates of a JTextField in a JFrame

I've added a JTextField in a JFrame using the BorderLayout . 我已经使用BorderLayoutJFrame添加了JTextField
Now I want to know the location of the JTextField . 现在我想知道JTextField的位置。

I used getX() and getLocation() , but both gives me 0 , which is not the right answer. 我使用了getX()getLocation() ,但是都给了我0 ,这不是正确的答案。
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. getLocation()方法在内容窗格中提供了组件相对于其父组件的位置,因此该位置实际上可能是0。此外,在框架可见之前,您不能调用该方法。

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 ). 在组件( JTextField )中调用getLocation()应该返回其对于父容器的坐标(在下面的示例中为JFrame )。

Note : You will have to do the layout in the container ( JFrame ) before getting the coordinates. 注意获取坐标之前 ,必须在容器( JFrame )中进行 布局
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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