1.整体的结构图:
2.编写GameFrame.java的代码:
package cn.bjsxt.test;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class GameFrame extends Frame {
Image image = GameUtil.getImage("images/sun.jpg");
public void launchFrame() {
setSize(500, 500);
setLocation(100, 100);
setVisible(true);
new PaintThread().start();
addWindowListener(new WindowAdapter() {
// 单击右键选择“source”中的“override/implement
// methods”,frame里面勾选“windowClosed”点击“OK”
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private double x = 100, y = 100;
// 单击右键选择“source”中的“override/implement
// methods”,window里面勾选“paint(graphic)”点击“OK”
@Override
public void paint(Graphics g) {
System.out.println("paint!!!");
g.drawLine(100, 100, 200, 200);
g.drawRect(100, 100, 200, 200);
g.drawOval(100, 100, 200, 200);
Font f = new Font("宋体", Font.BOLD, 30);
g.setFont(f);
g.drawString("第一次画图", 200, 200);
g.fillRect(100, 100, 20, 20);
Color c = g.getColor();
g.setColor(Color.red);
g.fillOval(300, 300, 20, 20);
g.setColor(c);
g.drawImage(image, (int) x, (int) y, null);
x += 3;
y += 3;
}
class PaintThread extends Thread {
public void run() {
while (true) {
repaint();
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
GameFrame gf = new GameFrame();
gf.launchFrame();
}
}
3.编写GameUtil.java的代码:
package cn.bjsxt.test;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class GameUtil {
private GameUtil() {
}
public static Image getImage(String path) {
URL u = GameUtil.class.getClassLoader().getResource(path);
BufferedImage image = null;
try {
image = ImageIO.read(u);
} catch (IOException e) {
e.printStackTrace();
}
return image;
}
}
4.运行之后的结果: