Question

Icon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );
ImageIcon bug = new ImageIcon( getClass().getResource( "bug1.png" ) );

What's the difference between these two? My book always uses the way in the first line to declare an ImageIcon but wouldn't it be better to declare it the second way because more specifically it is an ImageIcon?

Was it helpful?

Solution 2

Their nature and application is different. Image is an abstract superclass of all classes that represent graphical images. ImageIcon is an implementation of Icon interface that uses Image as its source.
Think of an Image as something that could be rendered and an ImageIcon as something that will be rendered as an Icon when its paintIcon() method is called.

Quoted from here
Hope this is what you're looking for ;)

OTHER TIPS

Icon is an Interface, whereas ImageIcon is an implementation of that interface.

The first is better because it means you can change your ImageIcon for another implementation of Icon later without needing to change the rest of your application.

You should start by taking a read through JavaDocs for ImageIcon.

You will notice that ImageIcon implements Icon, meaning that it can be used where ever an Icon is expected (such as JButton and JLabel for example) but it also provides the means by which you can obtain an instance of Image which allows you to paint it using Graphics without the need for a Component reference, which Icon needs

see java-imageicon-vs-image-difference

It is a thread about the difference between image and imageicon, but in the comments they also talk about Icon and such. Maybe this helps.

both are similar but the first one is the best because ImageIcon is Icon but not the reverse.When i say ImageIcon is Icon ImageIcon implements Icon.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top