4、Jpanel面板中加載背景圖片
在實際應用Java做界面的過程中,常常會涉及到加載背景圖片以使頁面美化。下面整理了一個小模塊以便於調用。
1 package com.tntxia.commonswing.panel; 2 3 import java.awt.*; 4 import javax.swing.JPanel; 5 6 /** 7 * 有背景圖片的Panel類 8 * @author tntxia 9 * 10 */ 11 public class BackgroundPanel extends JPanel { 12 13 /** 14 * 15 */ 16 private static final long serialVersionUID = -6352788025440244338L; 17 18 private Image image = null; 19 20 public BackgroundPanel(Image image) { 21 this.image = image; 22 } 23 24 // 固定背景圖片,允許這個JPanel可以在圖片上添加其他組件 25 protected void paintComponent(Graphics g) { 26 g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this); 27 } 28 }
調用程序示例如下:
1 Image image=new ImageIcon("images/bg.gif").getImage(); 2 JPanel panel = new BackgroundPanel(image);