创建一个用来画图像的工具类(GameUtil)
package com.zhushen.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(){
}
/**
* 根据path加载一张图片,返回Image
* @param path
* @return
*/
public static Image getImage(String path){
URL u=GameUtil.class.getClassLoader().getResource(path);
BufferedImage img=null;
try {
img=ImageIO.read(u);
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
}
在画窗口类中加载一个Image对象并把它画出来
package com.zhushen.Test;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* 游戏窗口类
* @author zhushen
*
*/
public class GameFrame extends Frame {
private static final long serialVersionUID = 1L;
Image img=GameUtil.getImage("images/mylove.png");
/**
* 加载游戏窗口
* @param x
* @param y
* @param width
* @param height
*/
public void launchFrame(int x,int y,int width,int height){
setSize(width,height);
setLocation(x,y);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
}) ;
}
/**
* 在窗口里面画元素
*/
public void paint(Graphics g){
g.drawImage(img, 100, 100, null);
}
public static void main(String[] args) {
GameFrame gf=new GameFrame();
gf.launchFrame(100,100,500,500);
}
}