Java ArrayList如何检查其中一个矩形是否包含鼠标?

时间:2015-03-28 12:01:09

标签: java

我有一个放置瓷砖的应用程序。你可以把瓷砖放在瓷砖上,但我不想要。我知道我需要像瓷砖矩形包含鼠标那样的东西,然后不要在它上面放一块瓷砖。但这并不奏效。看看这段代码:

for (int i = 0; i < b.toArray().length; i++) {
    b.get(i).tick();

    if (b.get(i).r.contains(Comp.mx, Comp.my)) {
        canPlaceATile = false;
        //  System.out.println("yes");
    }
    else {
        canPlaceATile = true;
        //System.out.println("no");
    }

    if (b.get(i).remove) {
        b.remove(i);
        i--;
    }
}

这是我检查鼠标是否位于其中一个区域内的方法。

Block class:

public abstract class block {

    public int x,id;
    public int y;
    protected Image img;
    public boolean remove;
    public int rotate;
    public Rectangle r;

    protected int bx, by;

    public block() {
    }

    public abstract void tick();

    public abstract void render(Graphics g);

    public void createCollisionRect() {
        r.setBounds(x - (int) play.camx, y - (int) play.camy, 20, 20);
    }
}

瓷砖的一个例子:

public class wall extends block {

    public wall(int x, int y, int rot) {
        this.x = x;
        this.y = y;
        this.rotate = rot;
        r = new Rectangle(x - (int) play.camx, y - (int) play.camy, 20, 20);
        id = 0;
    }

    public void tick() {
        createCollisionRect();

        if (Comp.mr && r.contains(new Point((Comp.mx), (Comp.my)))) {
            remove = true;
        }
    }

    public void render(Graphics g) {
        ImageIcon i62 = new ImageIcon("res/tiles/wall.png");
        img = i62.getImage();
        g.drawImage(img, x - (int) play.camx, y - (int) play.camy, null);

        g.setColor(Color.red);
        // g.drawRect(x -(int)play.camx, y - play.camy, 20,20);
    }
}

我想检查是否有任何矩形包含鼠标,如果鼠标位于其中一个矩形内,则将canPlaceATile设置为false。上面的代码不起作用,因为当我打印控制台并且我将鼠标放在其中一个磁贴上时,它说:

yes
no
yes
no
yes
no
yes
no
yes
no
yes
no
yes
no
yes
no
yes
no
yes
no
yes
no
yes

这是我的鼠标在矩形上而根本不移动它的时候。如何解决这个问题,以便我不能将瓷砖放在瓷砖上面。她是我放置瓷砖的地方:

public void mousePressed(MouseEvent e) {
    if (e.getButton() == MouseEvent.BUTTON1) {
        Comp.ml = true;
        if (manager.isplay && play.dragging == false) {
            if (play.canPlaceATile) {
                if (play.selectedID == 0) {
                    play.b.add(new wall((Comp.mx / 20) * 20, (Comp.my / 20) * 20, play.selectedRot));
                }
            }
        }
    }
}

0 个答案:

没有答案