这是一些代码,应该创建一个可以通过箭头键控制的椭圆形,我已经做了很多研究但是我找不到解决问题的方法。我正在使用Eclipse Mars和Java语言。这是我的代码。
package com.game;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Game extends Applet implements KeyListener, Runnable {
public int x,y;
public boolean up,down,left,right;
public Image offscreen;
public Graphics d;
public void init(){
setSize(854,480);
Thread th = new Thread(this);
th.start();
offscreen = createImage(854,480);
d = offscreen.getGraphics();
this.addKeyListener(new Game());
}
public void run(){
while(true)
{
System.out.println("X: " + x);
System.out.println("Y: " + y);
if(left == true){
x--;
}
if(right == true){
x++;
}
if(up == true){
y--;
}
if(down == true){
y++;
}
repaint();
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyTyped(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
System.out.println("Left key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
System.out.println("Right key pressed");
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = true;
System.out.println("Left key pressed");
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = true;
System.out.println("Left key pressed");
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
right = false;
}
}
public void paint (Graphics g){
d.clearRect(0, 0, 854, 480);
d.drawOval(x, y, 20, 20);
g.drawImage(offscreen, 0, 0, this);
}
public void update(Graphics g){
paint(g);
}
}
谢谢!