纸牌位图的加载
我已经通过别的方法得到一些纸牌的位图,并把它们放在yxc.card.common.images包中,怎样去把加载并显示出来?为此写了一个独立的LoadBufferedImage类,它有一个方法getImage(String id)来取到相应的位图。其中用到一个config.properties属性文件,用来指明id对应的位图文件相对LoadBufferedImage类路径的相对位置。LoadBufferedImage类在包yxc.card.util中。
LoadBufferedImage类的代码:
package yxc.card.util;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.imageio.ImageIO;
public class LoadBufferedImage {
private ResourceBundle config;
public LoadBufferedImage(String configFile) {
config = ResourceBundle.getBundle(configFile);
}
public BufferedImage getImage(String s) throws IOException{
BufferedImage bufferedImage = null;
java.net.URL url = null;
if (s == null){
System.out.println(s+" image is not exist.");
return null;
}
String s1;
try {
s1 = config.getString(s);
}catch (MissingResourceException missingresourceexception) {
System.out.println(s+" image is not exist.");
return null;
}
url = getClass().getResource(s1);
if (url != null) {
bufferedImage = ImageIO.read(url);
if(bufferedImage==null){
System.err.println("Failed to load image " + url + " for entry [" + s + "] .");
return null;
}
}else {
System.out.println(s+" image is not exist.");
}
return bufferedImage;
}
}
Config.properties文件放在包yxc.card.common.images包,它的部分内容如下:
1=../common/images/bmp170.bmp
2=../common/images/bmp158.bmp
3=../common/images/bmp159.bmp
4=../common/images/bmp160.bmp
5=../common/images/bmp161.bmp
6=../common/images/bmp162.bmp
7=../common/images/bmp163.bmp
8=../common/images/bmp164.bmp
9=../common/images/bmp165.bmp
10=../common/images/bmp166.bmp
11=../common/images/bmp167.bmp
12=../common/images/bmp168.bmp
13=../common/images/bmp169.bmp
这样,通过下面两语句,就可取到位图了。
LoadBufferedImage conf=new LoadBufferedImage("yxc.card.common.images.config");
BufferedImage image=conf.getImage("1");
为把位图显示于CardFace中,对CardFace类做一些修改:
在CardFace类中添加两个Field:
private BufferedImage image;
private AffineTransformOp op;
在CardFace类中添加loadImage()函数:
private void loadImage(){
String id="0";
if(card!=null){
id=card.toString();
}
try {
LoadBufferedImage conf=new LoadBufferedImage("yxc.card.common.images.config");
BufferedImage image=conf.getImage(id);
if(image!=null){
this.image=image;
this.repaint();
}
} catch (IOException e) {
e.printStackTrace();
}
}
在CardFace类中Override paintComponent方法来显示位图:
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
if(image!=null){
g2d.drawImage(image, op, 0, 0);
}
}
再修改CardFace构造函数,加入loadImage();行,如下黑体部分。
public CardFace(Card card) {
super();
this.card=card;
location=new Point(0,0);
initGUI();
loadImage();
}
至此,就能把位图取到,并在CardFace中显示了。