我正在做一个简单的项目,但我无法实现如何将可绘制对象作为(a)交叉移动。我的意思是,例如,当我同时按下向上和向左箭头键时,我希望我的可绘制对象准确地向西北方向移动。但是,通过在方法中使用简单的 if 语句KeyListener
,我无法实现它。有没有特殊的方法或额外的包装?这是我的代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
import javax.swing.JPanel;
public class Top extends JPanel implements ActionListener, KeyListener {
/**
*
*/
private static final long serialVersionUID = 1L;
Timer t = new Timer(5, this);
int xR = 0;int yR = 0; int zR = 0;
double x = 0, y = 0, xVel = 0, yVel = 0, width = 0, height = 0;
public Top() {
t.start();
setBackground(Color.black);
addKeyListener(this);
setFocusable(true);
}
public void actionPerformed(ActionEvent e) {
repaint();
x+=xVel;
y+=yVel;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(Color.blue);
g2d.fill(new Ellipse2D.Double(this.x, this.y, 50, 50));
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_DOWN) {
down();
}
if(keyCode == KeyEvent.VK_UP) {
up();
}
if(keyCode == KeyEvent.VK_RIGHT) {
right();
}
if(keyCode == KeyEvent.VK_LEFT) {
left();
}
}
public void down() {
this.yVel= 1;
this.xVel= 0;
}
public void up() {
this.yVel = -1;
this.xVel = 0;
}
public void left() {
this.xVel = -1;
this.yVel = 0;
}
public void right() {
this.xVel = 1;
this.yVel = 0;
}
@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_DOWN ||
keyCode == KeyEvent.VK_UP ||
keyCode == KeyEvent.VK_RIGHT ||
keyCode == KeyEvent.VK_LEFT ) {
xVel=0;
yVel=0;
}
}
}
*此代码只能将椭圆完全左上或下移动 *