介绍Introduction
本文展示了如何使用Java™来创建一个用来在Java™ 的applet和/或应用程序中展示图片的Swing类. 它还包括了使得图片渲染加快需要的步骤,还有在滚动容器中的使用方法.
为了更好的理解,特别是对于初学者而言,本文使用了 JImageComponent 的实现作为引用,它扩展了 Swing 的 Component.
说明
1. 创建一个子类
创建一个子类继承扩展你的类。其父类通常是Java™ Swing诸多类中的一个.
JImageComponent扩展了 Swing 的 JComponent:
1 2 3 4 5 6 7 8 | public class JImageComponent extends javax.swing.JComponent {
/**
* Constructs a new JImageComponent object.
*/
public JImageComponent() {
}
}
|
2. 创建类变量
你的类将需要几个变量来持有重要的数据. 通常,这将在你扩张类的功能时进行. 一般情况下,它至少要包含两个变量:一个BufferedImage对象用来持有需要绘制出来的图像,还有一个对应的 Graphics 对象.
JImageComponent 包含两个私有变量:
1 2 3 4 5 | /** Holds the <code>BufferedImage for the image. */
private BufferedImage bufferedImage = null ;
/** Holds the Graphics for the image. */
private Graphics imageGraphics = null ;
|
3. 实现图像的Set/Change功能
你的类将会绘制其变量所描述的图像。你可能需要实现在构造时设置图像,或者在运行期间设置或者修改图像的功能.
JImageComponent 允许在构造时设置图像,或者在运行期间设置或者修改图像. 简便起见,这里我只列出了一个构造器.
将一个BufferedImage作为参数的构造器.
1 2 3 4 5 6 7 8 9 | /**
* Constructs a new JImageComponent object.
*
* @param bufferedImage
* Image to load as default image.
*/
public JImageComponent(BufferedImage bufferedImage) {
this .setBufferedImage(bufferedImage);
}
|
JImageComponent 的方法用来在运行期间设置或者修改图像。至于为什么这个方法还要去设置组件的边界,将会在讨论实现用于滚动容器中的功能时解释.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /**
* Sets the buffered image, and updates the components bounds.
*
* @param bufferedImage
* The buffered image to set to.
*/
public void setBufferedImage(BufferedImage bufferedImage) {
this .bufferedImage = bufferedImage;
if ( this .bufferedImage == null ) {
this .imageGraphics = null ;
this .setBounds( 0 , 0 , 0 , 0 );
}
else {
this .imageGraphics = this .bufferedImage.createGraphics();
this .setBounds( 0 , 0 , this .bufferedImage.getWidth(), this .bufferedImage.getHeight());
}
}
|
4. 实现图片的设置/加载功能
你的类可能要实现通过从资源中加载一张图片来设置图像的功能. JImageComponent 允许通过提供一个加载由一个统一资源定位符(URL)作为参数来加载一张图像的方法,来使得位于应用程序包中的图像被加载. 请注意你可能需要在图像被加载之后通过调用 JImageComponet 的 repaint() 方法来对图像进行重新绘制. 1 2 3 4 5 6 7 8 9 10 11 12 | /**
* Loads image from URL.
*
* @param imageLocation
* URL to image.
* @throws Exception
* Throws an <code>IOException if file cannot be loaded.
*/
public void loadImage(URL imageLocation) throws IOException {
this .bufferedImage = ImageIO.read(imageLocation);
this .setBufferedImage( this .bufferedImage);
}
|
你可以任意实现必要多的方法。 例如JImageComponent,还会有一个用来加载一张由一个文件参数指定的图像的方法. 1 2 3 4 5 6 7 8 9 10 11 12 | /**
* Loads image from a file.
*
* @param imageLocation
* File to image
* @throws IOException
* Throws an <code>IOException if file cannot be loaded
*/
public void loadImage(File imageLocation) throws IOException {
this .bufferedImage = ImageIO.read(imageLocation);
this .setBufferedImage( this .bufferedImage);
}
|
|