package theChildOfGod.test;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
/**
* 游戏开发中常用的工具类(比如:加载图片等方法)
* @author theChildOfGod
*
*/
public class GameUtil {
private GameUtil() {}
public static Image getImage(String path) {
URL u = GameUtil.class.getClassLoader().getResource(path);
BufferedImage imag = null;
try {
imag = ImageIO.read(u);
} catch (IOException e) {
e.printStackTrace();
}
return imag;
}
}
package theChildOfGod.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;
import org.omg.Messaging.SyncScopeHelper;
/**
* 游戏窗口类
* @author theChildOfGod
*
*/
public class GameFrame extends Frame{
Image img = GameUtil.getImage("images/timg.jpg");
/**
* 加载窗口
*/
public void launchFrame() {
setSize(500, 500);
setLocation(100, 100);
setVisible(true);
new PaintThread().start();
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private double x = 100, y = 100;
private boolean left;
@Override
public void paint(Graphics g) {
g.drawImage(img, (int)x, (int)y, 200, 200, null);
if (left) {
x -= 3;
} else {
x += 3;
}
if (x > 500 - 200) {
left = true;
}
if (x < 0) {
left = false;
}
}
/**
* 定义一个重画窗口的线程类,是一个内部类。
* @author theChildOfGod
*
*/
class PaintThread extends Thread{
public void run() {
while(true) {
try {
repaint();
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
GameFrame gf = new GameFrame();
gf.launchFrame();
}
}