簡體   English   中英

在JFrame中獲取JTextField的坐標

[英]Getting coordinates of a JTextField in a JFrame

我已經使用BorderLayoutJFrame添加了JTextField
現在我想知道JTextField的位置。

我使用了getX()getLocation() ,但是都給了我0 ,這不是正確的答案。
那我怎么去那個位置呢?

getLocation()方法在內容窗格中提供了組件相對於其父組件的位置,因此該位置實際上可能是0。此外,在框架可見之前,您不能調用該方法。

如果要相對於框架的位置,則需要使用

SwingUtilities.convertPoint(...);

在組件( JTextField )中調用getLocation()應該返回其對於父容器的坐標(在下面的示例中為JFrame )。

注意獲取坐標之前 ,必須在容器( JFrame )中進行 布局
僅顯示布局即可完成布局。

范例

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