我正在进行斯坦福在线Java课程,我在移动划桨时遇到了麻烦。我的mouselistener
已全部连接起来,它产生的值似乎与我的鼠标正在做的一样。我从最后一个位置减去当前位置,这应该给我的桨的翻译值,但是有点麻烦。当我加载它时,屏幕底部出现了桨叶,但只要鼠标进入屏幕,桨就会飞走!!
注意 - 我已将输出包含到控制台中以显示应更新到paddle对象的X位置的值流。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Breakout extends Canvas implements MouseMotionListener, MouseListener{
private final int WIN_WIDTH = 500;
private final int WIN_HEIGHT = 700;
private final int BRICK_Y_POSITION = 100;
private final int BRICK_HEIGHT = 10;
private final int BRICK_WIDTH = 30;
//Create the paddle
private final int paddleYPosition = 500;
private int lastX = 0;
private int currentX = 0;
brick paddle = new brick(0,paddleYPosition, BRICK_WIDTH+20, BRICK_HEIGHT);
//Create Canvas object that implements the MouseListener and KeyListener
public Breakout(){
super();
addMouseListener(this);
addMouseMotionListener(this);
setBackground(Color.gray);
}
public void makeBricks(Graphics g, Color color, int yPosition){
int xSpacer = 0;
int ySpacer = 0;
int x = 15;
g.setColor(color);
for (int j= 0; j<2; j++){
for (int i=0; i<13; i++){
g.fillPolygon(new brick (x + xSpacer , yPosition + ySpacer , BRICK_WIDTH , BRICK_HEIGHT));
xSpacer+=35;}
ySpacer+=15;
xSpacer = 0;
}
}
public void paint (Graphics g){
makeBricks(g, Color.red, BRICK_Y_POSITION);
makeBricks(g, Color.orange, BRICK_Y_POSITION+30);
makeBricks(g, Color.yellow, BRICK_Y_POSITION+60);
makeBricks(g, Color.green, BRICK_Y_POSITION+90);
makeBricks(g, Color.cyan, BRICK_Y_POSITION+ 120);
g.setColor(Color.black);
g.fillPolygon(paddle);
paddle.translate(currentX - lastX, paddleYPosition);
}
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) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {
if (10 <= e.getX() && e.getX() <=490){
currentX = e.getX();
System.out.println(currentX-lastX);
lastX = currentX;
}
repaint();
}
public static void main(String[] args){
//Create canvas
Breakout canvas = new Breakout();
//Create JFrame to hold the canvas
JFrame win = new JFrame("Breakout!");
win.setSize(500,700);
//Add all of the visual elements to the JFrame window
win.add(new JLabel("TitledBorder using LineBorder"));
win.add(canvas);
win.setVisible(true);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}