[an error occurred while processing this directive]
[an error occurred while processing this directive]
public class Ivylet extends JApplet {
public void init() {
IvyPanel tp = new IvyPanel();
setContentPane(tp);
}
}
class IvyPanel extends JPanel {
Icon icon;
public IvyPanel() {
/** コンストラクタ 引数は画像が入っているパス */
setBackground(new Color(0x33, 0x33, 0x33)); // 背景色設定
setPreferredSize(new Dimension(300, 300)); // サイズ設定
icon = new Icon("http://funini.com/kei/ivy/narita/00.jpg");
icon.setPosition(new int[]{0, 0, 400, 300});
}
/** 描画を行う */
public void paintComponent(Graphics g) {
super.paintComponent(g); // ウィンドウを表示
Graphics2D g2 = (Graphics2D) g; // アンチエイリアスの設定など
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
icon.draw(g2); // 各アイコンを表示
}
}
abstract class Rect {
int[] P; // X,Y座標, 幅、高さ
Image img;
int imgW, imgH; // 画像の幅、高さ
public Rect(int x, int y, int w, int h) {
P = new int[] { x, y, w, h };
}
/** 画像をロード。path がhttp:// で始まる場合、HTTPで取得する */
public void loadImage(String path){
img = ImageLoader.load(path);
imgW = img.getWidth(null);
imgH = img.getHeight(null);
}
public void setPosition(int[] P){
for(int i = 0; i < 4; i++)
this.P[i] = P[i];
}
}
class Icon extends Rect {
int[] dest, orig; // 移動先と移動元のx, y, w, hを持つ配列
public Icon(String imgPath) {
super(0, 0, 0, 0);
loadImage(imgPath);
}
/** アイコンを描画する */
void draw(Graphics2D g) {
g.drawImage(img, P[0], P[1], P[0] + P[2],
P[1] + P[3], 0, 0, imgW, imgH, null);
}
}
ImageLoader il = new ImageLoader();
Image img = il.load("c:/hoge.jpg");
のように書かなくても、
Image img = ImageLoader.load("c:/hoge.jpg");
のように簡単に書くことが出来ます。
class ImageLoader {
/** 画像をロード。path がhttp:// で始まる場合、HTTPで取得する */
public static Image load(String path) {
try {
if(path.startsWith("http://")){
URLConnection urlc = new URL(path).openConnection();
return ImageIO.read(urlc.getInputStream());
}
return ImageIO.read(new File(path));
} catch (IOException ie) { ie.printStackTrace();}
return null;
}
}