1. 程式人生 > >swing JPanel設定背景圖 拉伸、平鋪、居中

swing JPanel設定背景圖 拉伸、平鋪、居中

/**
* 可設定背景圖片的JPanel,提供了三種顯示背景圖片的方式:居中、平鋪和拉伸。
* 未設定背景圖片的情況下,同JPanel。
*
* @author 003
*/
public class JImagePane extends JPanel
{
private static final long serialVersionUID = -8251916094895167058L;

/**
* 居中
*/
public static final String CENTRE = "Centre";

/**
* 平鋪
*/
public static final String TILED = "Tiled";

/**
* 拉伸
*/
public static final String SCALED = "Scaled";

/**
* 背景圖片
*/
private Image backgroundImage;

/**
* 背景圖片顯示模式
*/
private String imageDisplayMode;

/**
* 背景圖片顯示模式索引(引入此屬性有助於必要時擴充套件)
*/
private int modeIndex;

/**
* 構造一個沒有背景圖片的JImagePane
*/
public JImagePane()
{
this(null, CENTRE);
}

/**
* 構造一個具有指定背景圖片和指定顯示模式的JImagePane
* @param image 背景圖片
* @param modeName 背景圖片顯示模式
*/
public JImagePane(Image image, String modeName)
{
super();
setBackgroundImage(image);
setImageDisplayMode(modeName);
}

/**
* 設定背景圖片
* @param image 背景圖片
*/
public void setBackgroundImage(Image image)
{
this.backgroundImage = image;
this.repaint();
}

/**
* 獲取背景圖片
* @return 背景圖片
*/
public Image getBackgroundImage()
{
return backgroundImage;
}

/**
* 設定背景圖片顯示模式
* @param modeName 模式名稱,取值僅限於ImagePane.TILED ImagePane.SCALED ImagePane.CENTRE
*/
public void setImageDisplayMode(String modeName)
{
if(modeName != null)
{
modeName = modeName.trim();

//居中
if(modeName.equalsIgnoreCase(CENTRE))
{
this.imageDisplayMode = CENTRE;
modeIndex = 0;
}
//平鋪
else if(modeName.equalsIgnoreCase(TILED))
{
this.imageDisplayMode = TILED;
modeIndex = 1;
}
//拉伸
else if(modeName.equalsIgnoreCase(SCALED))
{
this.imageDisplayMode = SCALED;
modeIndex = 2;
}

this.repaint();
}
}

/**
* 獲取背景圖片顯示模式
* @return 顯示模式
*/
public String getImageDisplayMode()
{
return imageDisplayMode;
}

/**
* 繪製元件
* @see javax.swing.JComponent#paintComponent(Graphics)
*/
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);

//如果設定了背景圖片則顯示
if(backgroundImage != null)
{
int width = this.getWidth();
int height = this.getHeight();
int imageWidth = backgroundImage.getWidth(this);
int imageHeight = backgroundImage.getHeight(this);

switch(modeIndex)
{
//居中
case 0:
{
int x = (width - imageWidth) / 2;
int y = (height - imageHeight) / 2;
g.drawImage(backgroundImage, x, y, this);
break;
}
//平鋪
case 1:
{
for(int ix = 0; ix < width; ix += imageWidth)
{
for(int iy = 0; iy < height; iy += imageHeight)
{
g.drawImage(backgroundImage, ix, iy, this);
}
}

break;
}
//拉伸
case 2:
{
g.drawImage(backgroundImage, 0, 0, width, height, this);
break;
}
}
}
}
}