简体   繁体   中英

Why use ImageIcon rather than Image?

In what instance would I want to use ImageIcon to represent a picture file rather than an Image object? I've been searching and I've seen people say that you would use an ImageIcon object when dealing with images that will be part of the GUI, but I still don't understand the implications of this. In other words, what is the actual difference between the two object types and what situations are they each suited for?

An Image is an object representing the data model of a picture. An ImageIcon is a Swing component that draws an Image on the screen, and you have to provide it with the appropriate Image to draw (either by passing in an existing Image or by giving it enough information to find and load the image).

The relationship is similar to that between a String and a JTextField ; one is the representation of the data, and the other is the graphical component that draws it on the screen.

Image is an object that represents a bitmap: an array of pixels of different colors.

Icon is an object that can draw a rectangular piece of graphics. Since it is an interface (and a simple one too), you can imagine many different types of icons: drawing predefined vector graphics, generating images on the fly etc. Therefore it is a useful abstraction and is used by Swing components (buttons, labels).

ImageIcon is an object that IS an Icon , but HAS-A Image . That is - it draws graphics based on a specific image.

When you say "why should I be using an ImageIcon instead of Image" you miss the point: in fact you are using an Image either way.

The implementation is to not hold up the Swing thread.

Images that are created from a URL, filename or byte array are preloaded using MediaTracker to monitor the loaded state of the image.

Basically, then you can set an ImageIcon for a button without actually forcing it to be loaded beforehand.

This can be seen by having a very large icon and setting the Frame's icon to this image. Once set visible, it may take a few seconds to actually appear.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM