2013-01-22 29 views
1

當我編譯下面的代碼我得到的錯誤:誤差addMouseListener將

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

你能發佈確切的編譯錯誤嗎? – demaniak

+0

你可以把類Obj的代碼? –

+0

什麼類是「Obj」? – aboveyou00

回答

3

你不能添加一個鼠標監聽器到任何對象類型。 Obj必須擴展java.awt.Component爲了做到這一點。

1

正如丹指出的那樣 - 在對象層次結構中的任何位置都沒有「addMouseListener」方法。

我假設你想將它添加到你的Obj類。

+0

我已經嘗試實現MouseListener而不是Obj,但是我得到相同的編譯錯誤。或者我誤解了? –

+0

Nevermind,我按照Dan的建議擴展到了java.awt.Component,並且解決了這個問題。 –