欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  技术分享

重写JComponent加载图片_Java Swing显示图片例子

程序员文章站 2022-03-01 14:53:02
...

一、介绍

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

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

重写JComponent加载图片_Java Swing显示图片例子


二、代码分析

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