开发者

Why isn't my object moving on MouseMoved?

开发者 https://www.devze.com 2023-03-26 20:30 出处:网络
Simple question – why wouldn\'t an object move if it\'s the object of .move() inside onMouseMoved()? I\'m trying to write Breakout as part of the Stanford 106A exercises on iTunes U and for some reas

Simple question – why wouldn't an object move if it's the object of .move() inside onMouseMoved()? I'm trying to write Breakout as part of the Stanford 106A exercises on iTunes U and for some reason I can't get the paddle to track the mouse. I'm a java noob, so I'm sure it's something really simple. Could someone please take a look at this code?

/** Runs the Breakout program. */
    public void run() {
        setupBoard();
        addMouseListeners();
    }

    /** Provides the initial GCanvas and blocks for the game */
    private void setupBoard(){
        this.setSize(开发者_开发技巧APPLICATION_WIDTH,APPLICATION_HEIGHT);
        addBricks();
        paddle = new GRect(PADDLE_WIDTH, PADDLE_HEIGHT);
        add(paddle, WIDTH/2-PADDLE_WIDTH/2,HEIGHT-PADDLE_Y_OFFSET);

    }

    public void MouseMoved(MouseEvent e){
        paddle.move(e.getX()-paddle.getX(), 0);
        }

    private GRect paddle;
}

I'm not sure if having paddle be an instance variable is appropriate in this case, since its "value" doesn't change (the paddle's always the paddle), but if I just define it as a new GRect within setupBoard I get an error in the MouseMoved() method.


Your class that has the mouseMoved() method needs to implement the interface MouseMotionListener, and add the motion listener. Moreover, the event handler is mouseMoved() not MouseMoved(). So, e.g.:

public class Game extends JPanel implements MouseMotionListener {
    public void run() {
        addMouseMotionListener(this);
        //...        
    }
    public void mouseMoved(MouseEvent e) {                  
        paddle.move(e.getX()-paddle.getX(), 0); 
    } 
    //...
};  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号