首页 > 解决方案 > 在 swing 中查找特定位置的所有组件

问题描述

我目前正在尝试将碰撞检测添加到我的 Java 游戏中。

这是我尝试做的一个例子:

public class Player extends JLabel {
    
    public String Name;
    public ImageIcon Image;
    public float Speed;
    
    public Player() {
        this.setBounds(new Rectangle (16,16));
    }
    
    public boolean isSameLayerAs(Component component) {
        
         if (JLayeredPane.getLayer(this) == application.Layer.getLayer(component) + 1) { 
             return true;
         } else {
             return false;
         }
    }
    
    public void movePlayer() {
        
        theLayer layer = application.Layer;

        Component ObjectAbove = layer.getComponentAt(this.getLocation().x + 8, this.getLocation().y + 14);
        
        
        
        if (ObjectAbove == null || (!isSameLayerAs(ObjectAbove) && this.getBounds().intersects(ObjectAbove.getBounds()))) {
            moveUp();
        }
        else if (ObjectAbove == null || (!isSameLayerAs(ObjectAbove) && !this.getBounds().intersects(ObjectAbove.getBounds()))) {
            moveUp();
        }
        layer.setLayer(this, ((this.getLocation().y) / 16) + 1);
    }
}

播放器大小为 16x16 像素。在 MovePlayer() 方法中,它将播放器上方的对象层与播放器的层进行比较。如果玩家与对象相交并且与对象具有相同的层,则玩家无法向上移动。对象的层是 y 位置除以 16。为了将对象置于玩家上方,我尝试使用 getComponentAt(),如果我选择玩家不在的位置,它就可以正常工作,例如:

this.getLocation().y - 1

然而,我希望玩家将对象重叠一点。 像这样的东西

所以我尝试了layer.getComponentAt(this.getLocation().x + 8, this.getLocation().y + 14);

getComponentAt() 然而返回播放器,因为播放器也在这个位置(播放器大小为 16x16 像素)。

所以我的问题是:有没有办法在特定位置找到所有组件?

标签: javaswingjlabel

解决方案


推荐阅读