代码改变世界

在Applet和Application中加载图片

2011-09-16 16:13  Rollen Holt  阅读(1045)  评论(0编辑  收藏  举报

先看看在Applet中加载图片把:

package Pictures;

/**
 * 在Applet中加载图片
 * */
import java.awt.Graphics;
import java.awt.Image;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JApplet;

public class JAppletDemo extends JApplet{
	@Override
	public void init(){
		try{
			img = getImage(new URL(
					"http://tp2.sinaimg.cn/1882500857/180/5609472576/1"),
					"rollen");
		}catch(MalformedURLException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		height = img.getHeight(this);
		weight = img.getWidth(this);
	}

	@Override
	public void paint(Graphics g){
		super.paint(g);
		g.drawImage(img, 0, 0, weight, height, this);
	}

	private Image img;
	int height;
	int weight;
}

 然后在Application中加载图片

package Pictures;

/**
 * 在Application中加载图片
 * */
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JFrame;

public class ApplicationPicture extends JFrame{
	public ApplicationPicture(){
		Toolkit toolkit = Toolkit.getDefaultToolkit();
		try{
			img = toolkit.getImage(new URL(
					"http://tp2.sinaimg.cn/1882500857/180/5609472576/1"));
		}catch(MalformedURLException e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		validate();
		setSize(100, 100);
		setVisible(true);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	@Override
	public void paint(Graphics g){
		super.paint(g);
		g.drawImage(img, 0, 0, this);
	}

	public static void main(String[] args){
		new ApplicationPicture();
	}

	private Image img;
}