如何获取动态添加的JLabel的JPanel中的getLocation()?
我动态创建了许多 JLabel,并使用以下代码将它们添加到 JPanel(代码应该足以理解我希望的问题!)。
JPanel textPanel = new JPanel();
map = new HashMap<Integer,JLabel>();
vec = new Vector<JLabel>();
for(int i = 0; i<getCount();i++){ // getCount() returns int
JLabel label = new JLabel(getItemText(i)); // getItemText() returns String
map.put(i, label);
vec.add(label);
textPanel.add(map.get(i));
}
现在,我尝试访问这些标签的位置,但在尝试通过以下代码访问它们时,除了 java.awt.Point[x=296,y=63] 之外什么也得不到。
System.out.println("Component position [1]: " +
textPanel.getComponent(1).getLocationOnScreen());
我对所有组件都获得相同的位置,而不仅仅是一个组件。
另外(更重要的是)我得到了以下代码的位置 java.awt.Point[x=0,y=0]
。
System.out.println("Position of Component 1: " + map.get(1).getLocation());
我猜这与 JLabels 是动态创建的事实有关。然而,我确实需要动态创建它们,而且确实需要能够通过getLocation()
获取它们的位置。
请帮忙!也许有另一种方法来创建它们或以不同的方式访问它们的位置?
I have created a number of JLabels dynamically and have added them to a JPanel with the following code (code should be enough to understand the problem I hope!).
JPanel textPanel = new JPanel();
map = new HashMap<Integer,JLabel>();
vec = new Vector<JLabel>();
for(int i = 0; i<getCount();i++){ // getCount() returns int
JLabel label = new JLabel(getItemText(i)); // getItemText() returns String
map.put(i, label);
vec.add(label);
textPanel.add(map.get(i));
}
Now I am trying to access the Location of these labels but get nothing but java.awt.Point[x=296,y=63]
for them when trying to access them via the following code.
System.out.println("Component position [1]: " +
textPanel.getComponent(1).getLocationOnScreen());
I get the same position for all Components, not just for the one.
Also (more importantly) I get the position java.awt.Point[x=0,y=0]
for the following code.
System.out.println("Position of Component 1: " + map.get(1).getLocation());
I'm guessing this is to do with the fact that the JLabels are created dynamically. I really need to create them dynamically, however, and also really need to be able to get their Location via getLocation()
.
Please help! Perhaps there is another way to create them or a way to access their Location(s) differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当你创建一个组件时,它的默认位置是 (0, 0);
将组件添加到面板不会更改此位置。
将所有标签添加到面板后,您需要执行以下操作:
这将调用面板使用的布局管理器,然后根据布局管理器的规则为每个标签分配适当的位置。
When you create a component it has a default location of (0, 0);
Adding a component to a panel does NOT change this location.
After adding all the labels to the panel you need to do:
This will invoke the layout manager used by the panel and each label will then be assigned a proper location based on the rules of the layout manager.
这是一个 SSCCE。
典型输出
Here is an SSCCE.
Typical output