package com.sot.he.upload;
import java.awt.Graphics;
import java.awt.Image;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
/**
* 可设置背景图片的JPanel <br>
* 提供了三种显示背景图片的方式:居中、平铺和拉伸
*
* @author maxiang
*/
public class PicPanel extends JPanel {
private static final long serialVersionUID = -8251916094895167058L;
private Image image;// 背景图片
/**
* 背景图片显示模式索引(引入此属性有助于必要时扩展)
*/
private int modeIndex;
public PicPanel(String imgPath, int modeIndex) {
this.modeIndex = modeIndex;
try {
image = ImageIO.read(new FileInputStream(imgPath));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 构造一个具有指定背景图片和指定显示模式的JImagePane
*
* @param image
* 背景图片
* @param modeType
* 背景图片显示模式
*/
public PicPanel(Image image, int modeIndex) {
super();
this.image = image;
this.modeIndex = modeIndex;
}
/**
* 获取背景图片
*
* @return 背景图片
*/
public Image getBackgroundImage() {
return image;
}
/**
* 绘制组件
*
* @see javax.swing.JComponent#paintComponent(Graphics)
*/
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// 如果设置了背景图片则显示
if (image == null) {
return;
}
int width = this.getWidth();
int height = this.getHeight();
int imageWidth = image.getWidth(this);
int imageHeight = image.getHeight(this);
switch (modeIndex) {
// 居中
case 0: {
int x = (width - imageWidth) / 2;
int y = (height - imageHeight) / 2;
g.drawImage(image, x, y, this);
break;
}
// 平铺
case 1: {
for (int ix = 0; ix < width; ix += imageWidth) {
for (int iy = 0; iy < height; iy += imageHeight) {
g.drawImage(image, ix, iy, this);
}
}
break;
}
// 拉伸
case 2: {
g.drawImage(image, 0, 0, width, height, this);
break;
}
}
}
/**
* 居中
*/
public static final int CENTRE = 0;
/**
* 平铺
*/
public static final int TILED = 1;
/**
* 拉伸
*/
public static final int SCALED = 2;
}