1

当我编译以下代码时,我得到了错误:

The method addMouseListener(Player) is undefined for the type Player

代码:

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class Player extends Obj implements MouseListener {

    public Player() {
        super();
        addMouseListener(this);
    }

    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
}

这是Obj类的代码:

import java.awt.Rectangle;
import java.util.ArrayList;

public class Obj {

    protected int x, y, width, height, dx, dy, depth;
    protected double speed, direction;
    protected Rectangle bound;
    protected ArrayList<Obj> collideList;

    public Obj() {
        bound = new Rectangle(x, y, width, height);
        collideList = new ArrayList<>();
    }

    public boolean checkCollision(Obj obj1, Obj obj2) {
        boolean collide = false;

        // Temporarily move bound to where it will be next step, 
            //to anticipate a collision
        // (this is important to make sure objects don't "stick" 
            // to each other)
        obj1.getBound().translate(obj1.getDx(), obj1.getDy());
        // If their bounds intersect, they have collided
        if (obj1!=obj2 && obj1.getBound().intersects(obj2.getBound())) {
            collide = true;
        } else {
            // Move the bound back
            bound.translate(-obj1.getDx(), -obj1.getDy());
        }

        return collide;
    }

    public void step() {
        bound.setBounds(x, y, width, height);
    }

    public Rectangle getBound() {
        return bound;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getDy() {
        return dy;
    }

    public int getDx() {
        return dx;
    }

    public void setX(int x) {
        this.x = x;
    }

    public void setY(int y) {
        this.y = y;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }
}
4

2 回答 2

3

您不能将鼠标侦听器添加到任何对象类型。Obj必须扩展java.awt.Component才能做到这一点。

于 2013-01-22T21:52:29.370 回答
1

正如 Dan 指出的那样 - 在对象层次结构中的任何地方都没有“addMouseListener”方法。

我假设您希望将其添加到您的 Obj 类中。

于 2013-01-22T21:54:56.357 回答