---
title: "Swing 在就JPanel加背景【转】"
author: "弦上的福音"
date: "2014-04-10T10:19:02Z"
tags: []
categories: ["编程语言"]
slug: "swing-jpanel"
draft: false
lastmod: "2014-04-10T10:19:02Z"
id: 2042851
url: "https://1574468392.iteye.com/blog/2042851"
---

```
package com.tntxia.commonswing.panel;  
  
import java.awt.*;  
import javax.swing.JPanel;  
  
/** 
 * 有背景图片的Panel类 
 * @author tntxia 
 * 
 */  
public class BackgroundPanel extends JPanel {  
      
    /** 
     *  
     */  
    private static final long serialVersionUID = -6352788025440244338L;  
      
    private Image image = null;  
  
    public BackgroundPanel(Image image) {  
        this.image = image;  
    }  
  
    // 固定背景图片，允许这个JPanel可以在图片上添加其他组件  
    protected void paintComponent(Graphics g) {  
        g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);  
    }  
}  
```

 调用方法：

```
Image image=new ImageIcon("images/bg.gif").getImage();  
JPanel panel = new BackgroundPanel(image);
```