不久前我开始把学习java作为一种爱好,因为我想做一个小游戏。我学习了java的基础知识,我决定尝试解决game-dev。我的 JFrame 和一切都很好,从技术上讲我没有错误,但我的小矩形家伙不会在屏幕上移动。这是我的代码:
package main;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class Race extends JFrame {
public int speed=5;
public int up=1;
public int left=2;
public int down=3;
public int right=4;
public int direction=0;
Rectangle p1 = new Rectangle (500,400,20,40);
public Race()
{
super("Race");
setSize(1000,800);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cont=getContentPane();
cont.setBackground(Color.orange);
setResizable(false);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.red);
g.fillRect(p1.x, p1.y, p1.width, p1.height);
}
public class Move extends Thread implements KeyListener
{
public void run()
{
addKeyListener(this);
while(true)
{
try
{
repaint();
if(direction==up)
{
p1.y-=(int)speed;
}
if(direction==down)
{
p1.y+=(int)speed;
}
if(direction==right)
{
p1.x+=(int)speed;
}
if(direction==left)
{
p1.x-=(int)speed;
}
Thread.sleep(75);
}
catch (Exception e)
{
break;
}
}
}
@Override
public void keyPressed(KeyEvent event) {
// TODO Auto-generated method stub
}
@Override
public void keyReleased(KeyEvent event) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent event) {
// TODO Auto-generated method stub
if(event.getKeyChar()=='w')
{
direction = up;
}
if(event.getKeyChar()=='d')
{
direction = left;
}
if(event.getKeyChar()=='s')
{
direction = down;
}
if(event.getKeyChar()=='a')
{
direction = left;
}
}
}
public static void main(String[] args)
{
new Race();
}
}