代码拉取完成,页面将自动刷新
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TankClient6 extends Frame {
int x = 50, y = 50;
Image offScreenImage = null;
public static final int GAME_WIDTH=800;
public static final int GAME_HEIGHT=600;
public void paint(Graphics g) {
Color c = g.getColor();
g.setColor(Color.RED);
g.fillOval(x, y, 30, 30);
g.setColor(c);
y += 5;
}
public void launchFrame() {
this.setLocation(300, 50);
this.setSize(GAME_WIDTH, GAME_HEIGHT);
this.setBackground(Color.green);
this.setTitle("TankWar");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setResizable(false);
setVisible(true);
this.addKeyListener(new KeyMonitor());
setVisible(true);
new Thread(new PaintThread()).start();
}
private class KeyMonitor extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
switch (key) {
case KeyEvent.VK_LEFT:
x -= 5;
break;
case KeyEvent.VK_UP:
y -= 5;
break;
case KeyEvent.VK_RIGHT:
x += 5;
break;
case KeyEvent.VK_DOWN:
y += 5;
break;
}
}
}
private class PaintThread implements Runnable {
//内部类 (可以方便的访问包装类的方法。不方便公开的,只为包装类服务的类应当定义为内部类)
@Override
public void run() {
while (true) {
repaint();//会自动调用update方法
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void update(Graphics g){
if(offScreenImage==null){
offScreenImage=this.createImage(GAME_WIDTH,GAME_HEIGHT);
}//拿到这个图片的颜色
Graphics gOffScreen=offScreenImage.getGraphics();
Color c=gOffScreen.getColor();
gOffScreen.setColor(Color.green);
gOffScreen.fillRect(0,0,GAME_WIDTH,GAME_HEIGHT);
gOffScreen.setColor(c);
print(gOffScreen);
g.drawImage(offScreenImage,0,0,null);
}
public static void main(String[] args) {
TankClient6 tankClient6=new TankClient6();
tankClient6.launchFrame();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。