原理:我们直接在最上层容器内重写paintComponent(Graphics g)方法在容器中画一张图
片。(这种方法很直观,原理很简单) 具体步骤:
只需要在构造JPanel时重写paintComponent(Graphics g)就ok了。
class PanelTest extends JPanel{
ImageIcon background = new ImageIcon("background.jpg");//加载图片 Image im=Toolkit.getDefaultToolkit().getImage("background.jpg"); int h,w;
public void paintComponent(Graphics g) { g.drawImage(im, 0, 0, null);
} }
JPanel jpa = new JPanel(){
public void paintComponent(Graphics g) {
super.paintComponent(g);
ImageIcon img = new ImageIcon("image/449jdt.jpg");
g.drawImage(img.getImage(),0,0,null);
}
};
Toolkit
的子类被用于将各种组件绑定到特定本机工具包实现。
大多数应用程序不应直接调用该类中的任何方法。
Toolkit
定义的方法是一种“胶水”,将
java.awt
包中与平台无关的类与
java.awt.peer
中的对应物连接起来。
Toolkit
定义的一些方法能直接查询本机操作系统。
以下是采用ToolKit读取硬盘上的图片
private static Toolkit tk =Toolkit.getDefaultToolkit(); //拿到默认工具包,通过工具包的方法把硬盘上的图片拿到内存中来
private static Image[] exploreImages = null;
private static Map<String,Image> map = new HashMap<String,Image>();
static{
//静态代码区, “静态块”中代码的特点是:在这个类被装载时就会执行,且只执行一次。
exploreImages = new Image[]{
tk.getImage(Explore.class.getClassLoader().getResource("images/effect_blast_1.png")),
tk.getImage(Explore.class.getClassLoader().getResource("images/effect_blast_2.png")),
tk.getImage(Explore.class.getClassLoader().getResource("images/effect_blast_3.png")),
tk.getImage(Explore.class.getClassLoader().getResource("images/effect_blast_4.png")),
tk.getImage(Explore.class.getClassLoader().getResource("images/effect_blast_5.png"))
tk.get
};
}