JPanel image Background

在这里找到的。
[url]http://topic.csdn.net/u/20090326/21/a4ca9989-631e-42d1-8f4e-7d6cd6efa14f.html[/url]

原来核心是重载paintComponent绘制方法。原来的代码给我改过了。先看原代码会好点,他的注释很详细!

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;

import javax.swing.JPanel;

public class JImagePanel extends JPanel
{
public static final int TENSILE = 1; // 拉伸
public static final int CENTRE = 2; // 居中
public static final int TILED = 3; // 平铺

private Image backGround = null;
private int displayMode = 2;

public JImagePanel(String image, int displayMode)
{
this(Toolkit.getDefaultToolkit().getImage(image), displayMode);
}

public JImagePanel(Image image, int displayMode)
{
super();
this.displayMode = displayMode;
backGround = image;
}

protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (backGround != null)
{
int width = getWidth();
int height = getHeight();
int imageWidth = backGround.getWidth(this);
int imageHeight = backGround.getHeight(this);

switch (displayMode)
{
case CENTRE:
{
int x = (width - imageWidth) / 2;
int y = (height - imageHeight) / 2;
g.drawImage(backGround, x, y, this);
break;
}
case TILED:
{
for (int ix = 0; ix < width; ix += imageWidth)
{
for (int iy = 0; iy < height; iy += imageHeight)
{
g.drawImage(backGround, ix, iy, this);
}
}
break;
}
case TENSILE:
{
g.drawImage(backGround, 0, 0, width, height, this);
break;
}
}
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值