背景知识Component类提供了和绘图有关的三个方法分别是
paint(Graphicsg) 而paint()方法在加载窗口时会被自动调用
update(Graphicsg)
repaint()
调用repaint()可以实现绘图的更新,repaint会先调用update()方法,而update()方法会调用paint()方法实现图像的重绘
在原来的代码中添加如下的代码(红色为添加的代码)
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class TankClient extends Frame{
public void paint(Graphics g){
Color c=g.getColor();//保存现在的前景色,方便恢复
g.setColor(Color.red);//坦克的颜色设置为红色
g.fillOval(50, 50, 30, 30);//画我们的坦克
g.setColor(c);//注意千万不要改变原来的前景色
}
public void lunchFrame(){
this.setBackground(Color.green);
this.setLocation(400,300);
this.setSize(800, 600);
setVisible(true);
this.setResizable(false);
this.setTitle("坦克大战");
this.addWindowListener(new WindowAdapter(){
@Override
public void windowClosing(WindowEvent e){
System.exit(0);//最重要的逻辑控制代码
}
});
}
public static void main(String[] args) {
TankClient tc =new TankClient();
tc.lunchFrame();
}
}
就可以实现以下功能