当我编译以下代码时,我收到错误:
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;
}
}
答案 0 :(得分:3)
您无法将鼠标侦听器添加到任何对象类型。 Obj
必须延长java.awt.Component
才能执行此操作。
答案 1 :(得分:1)
正如Dan指出的那样 - 在对象层次结构中的任何地方都没有“addMouseListener”方法。
我假设你想把它添加到你的Obj类。