我如何使用鼠标事件移动球拍?

时间:2016-05-10 18:12:12

标签: java

我制作了一个迷你网球比赛,使用keylistener左右移动球拍。

package mini_tennis;
import java.awt.Rectangle;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;

public class Racquet {
private static final int Y = 330;
private static final int WIDTH = 60;
private static final int HEIGHT = 10;
int x = 0;
int xa = 0;
private Game game;

public Racquet(Game game) {
    this.game= game;
}

public void move() {
    if (x + xa > 0 && x + xa < game.getWidth()-60)
        x = x + xa;
}

public void paint(Graphics2D g) {
    g.fillRect(x, 330, 60, 10);
}

public void keyReleased(KeyEvent e) {
    xa = 0;
}

public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_LEFT)
        xa = -game.speed;
    if (e.getKeyCode() == KeyEvent.VK_RIGHT)
        xa = game.speed;
}

public Rectangle getBounds() {
    return new Rectangle(x, Y, WIDTH, HEIGHT);
}

public int getTopY() {
    return Y;
 }
}

我想知道如何使用鼠标事件移动球拍。例如,当我使用左按钮点击球拍时,它将向左或向右拖动球拍。你是否也可以通过左右移动我的鼠标而不按任何按钮来包括我如何移动球拍。

1 个答案:

答案 0 :(得分:0)

你需要一个鼠标监听器

public class Racquet {
 ...

  public void moveM(int mx)
  {
    x = mx; //invoked from panel to move the racquet
  }

 ...
}

您的小组课程:

class yourPanelClass implements MouseListener {
...
panel.addMouseListener(this); //add listener to the panel
Racquet raq = new Racquet(); //create the racquet
...
    @Override
    public void mouseClicked(MouseEvent e) {
       raq.moveM(e.getX()+((int)raq.getWidth()/2)); 
// get pointer position on mouse press and invoke method 
// in Racquet passing the current X location of the pointer
// subtracting half of the width of the racquet thus positioning it in
// the middle.
    }


    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent  e) {}

    @Override
    public void mousePressed(MouseEvent e) {}
....

}