我正在研究一個簡單的項目,但我無法實現如何將一個可繪製對象移動爲(a)十字。我的意思是,例如,當我同時向上按下左箭頭鍵時,我希望我的繪圖向西北方向移動。但是,通過在KeyListener
方法中使用簡單的if語句,我無法實現它。有沒有一種特殊的方式來做到這一點或有額外的包裝?這裏是我的代碼:java移動球
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;
}
}
}
* 這個代碼只能移動究竟向左向右向上或向下*
您可能需要發佈您的代碼才能獲得幫助。 – Jonatan 2012-04-11 13:50:06
我們不知道你已經嘗試過沒有一些代碼看,請張貼一些,所以我們不必猜測解決方案 – Chris 2012-04-11 13:50:58
看到接受的答案在這裏:http://stackoverflow.com/questions/752999/如何處理多個按鍵在java中 - 多鍵沒有「事件」,因爲鍵盤將它們作爲單獨的事件發送 – 2012-04-11 13:56:21