【发布时间】:2012-08-27 01:04:12
【问题描述】:
public Textures()
{
super(new GridBagLayout());
layout.add(l1);
layout.add(l2);
add(layout);
String[] T = filerw.fileRead2();
if(T[0].equals("11"))
{
rect1.setLocation(layout.getComponent(1).getBounds().getLocation());
}
if(T[0].equals("12"))
{
rect1.setLocation(layout.getComponent(2).getBounds().getLocation());
}
l1.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent arg0)
{
a = 11;
filerw.fileWrite();
rect1.setLocation(l1.getBounds().getLocation().x, l1.getBounds().getLocation().y);
}
});
l2.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent arg0)
{
a = 12;
filerw.fileWrite();
rect1.setLocation(l2.getBounds().getLocation().x, l2.getBounds().getLocation().y);
repaint();
}
});
我尝试了很多方法来确定组件的位置,但它们要么出错,要么显示为零,要么位置不正确。我尝试过 getX() 和 x、getBounds.getLocation、getLocation、getLocationOnScreen、layout.getComponent(1) 或 l1。如何找到组件的位置?我想得到一个矩形来包围图像,我该如何完成定位?
【问题讨论】:
-
如果您没有很快得到合适的答案,请考虑创建并发布sscce,这是一个我们可以运行的小型可编译和可运行程序,它将向我们展示您的问题。另外,在发布代码时,请使用一致的易于阅读的缩进。别人的代码很难理解,所以你不想让你的代码缩进乱七八糟,让我们更难理解。
-
另外,让我们确保您了解组件的位置是相对于其容器的。所以 l2 的位置将相对于包含它的布局容器。
-
我猜这是因为侦听器被添加到了与您预期不同的组件中。对于比猜测更好的事情,请遵循@HovercraftFullOfEels 的建议。
-
在调用
validate()或pack()之前,布局位置无效。还要考虑在封闭组件上使用setBorder()。 -
垃圾,谢谢!我没有想到 setBorder() 的想法!
标签: java swing components label