重写JComponent加载图片_Java Swing显示图片例子
2014-11-26 12:48:16  By: shinyuu

一、介绍

本文介绍了如何在Java™小应用程序和/或应用程序中创建显示图像、本文的方法是使用Swing类、使用Swing的优点是/使呈现的图像速度快、可用在滚动的容器

为了更好地理解、尤其是对初学者来说、本文采用JImageComponent实现、它继承了Swing的JComponent、程序运行效果

JImageComponent实现


二、代码分析

1、JImageComponent extends Swing´s JComponent

public class JImageComponent extends 
	javax.swing.JComponent {

    public JImageComponent() {
    }    
}

2、创建类变量

你的类将需要不同的变量来保存重要的数据、他们有可能转变为类的功能扩展、在一般情况下、它应该至少包含两个变量:一个BufferedImage对象持有的形象画、其相应的图形对象、

private BufferedImage bufferedImage = null;
private Graphics imageGraphics = null;

3、实现功能设置/更改图像

public void setBufferedImage(BufferedImage bufferedImage) {
	this.bufferedImage = bufferedImage;
	
	//Clear the graphics object if null image specified.
	//Clear the component bounds if null image specified.
	if (this.bufferedImage == null) {
		this.imageGraphics = null;
		this.setBounds(0, 0, 0, 0);
	}
	// Set the graphics object.
	// Set the component´s bounds.
	else {
		this.imageGraphics = this.bufferedImage.createGraphics();
		this.setBounds(0, 0, this.bufferedImage.getWidth(), 
			this.bufferedImage.getHeight());
	}
}

4、加载图像

public void loadImage(URL imageLocation) 
		throws IOException {
	this.bufferedImage = ImageIO.read(imageLocation);
	this.setBufferedImage(this.bufferedImage);
}

public void loadImage(File imageLocation) 
		throws IOException {
	this.bufferedImage = ImageIO.read(imageLocation);
	this.setBufferedImage(this.bufferedImage);
}

5、绘制图像

@Override
public void paint(Graphics g) {
	// Exit if no image is loaded.
	if (this.bufferedImage == null) {
		return;
	}
	
	// Paint the visible region.
	Rectangle rectangle = this.getVisibleRect();
	paintImmediately(g, rectangle.x, rectangle.y, 
		rectangle.width, rectangle.height);
};

@Override
public void paintImmediately(int x, int y, 
	int width, int height) {
	// Exit if no image is loaded.
	if (this.bufferedImage == null) {
		return;
	}
	
	// Paint the region specified.
	this.paintImmediately(super.getGraphics(), 
		x, y, width, height);
}

@Override
public void paintImmediately(Rectangle rectangle) {
	// Exit if no image is loaded.
	if (this.bufferedImage == null) {
		return;
	}
	// Paint the region specified.
	this.paintImmediately(super.getGraphics(), rectangle.x, 
		rectangle.y, rectangle.width, rectangle.height);
}


使用JImageComponent的时候要调用repaint()方法/编辑图像

最后给大家贴上实现了上面这个封装类的一个小例子、希望对大家有用

源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1mgn5bw0 密码: nodh

若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力

想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)

或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)

如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教

为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)

感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛


快速评论


技术评论

  • 该技术还没有评论、赶快抢沙发吧...
DD记账
top
+