重写JLabel,用于自定义显示图片


import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JLabel;

/**
* 重写JLabel,用于自定义显示图片
* @author RuiLin.Xie - xKF24276
*
*/
public class DiyJLabel extends JLabel
{
//图片路径
private String imgPath;

//显示样式
private ShowStyle style;

//图片
private Image img;

/**
* 设置图片路径及显示样式
* @param path
*/
public void setImage(String path, ShowStyle style)
{
imgPath = path;
this.style = style;

try
{
img = ImageIO.read(new File(imgPath));
}
catch (IOException e)
{
e.printStackTrace();
}
}

/**
* 重写label绘画方法
*/
@Override
protected void paintComponent(Graphics g)
{
Image img = getImage();

if(ShowStyle.ORIGINALLY == style && img != null)
{
//图片原始像素
g.drawImage(img, 0, 0, img.getWidth(this), img.getHeight(this), this);
}
else if(ShowStyle.ZOOM == style && img != null)
{
//缩放到与label同大小
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
}
else if(style == null && img != null)
{
//图片原始像素
g.drawImage(img, 0, 0, img.getWidth(this), img.getHeight(this), this);
}

super.paintComponent(g);
g = null;
}

/**
* 得到设置图片
* @return
*/
public Image getImage()
{
return img;
}
}

/**
* 显示样式
* @author RuiLin.Xie - xKF24276
*/
enum ShowStyle
{
/** 原始像素 **/
ORIGINALLY,

/** 缩放到与Label同大小 **/
ZOOM
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值