Divine Davis
Divine Davis

Reputation: 552

Adding an image in Java

I am getting an error: Image is abstract; cannot be instantiated in line 39. In line 45, the error cannot find symbol.

enter image description here

Upvotes: 1

Views: 2234

Answers (5)

user1283559
user1283559

Reputation: 49

You need to pass gun1 as a parameter to your drawGun method, or declare gun1 as a member variable.

Image is an abstract class, it cannot be instanced. You can read more about abstract class here https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html

To get an instance of Image you can use a class that will take care of that for you like ImageIO or something like this

ImageIcon image = new ImageIcon((Thread.currentThread().getContextClassLoader().getResource(url)));

Bonus using ImageIcon will let you draw animated gif.

Upvotes: 0

Dimitri_Wayland
Dimitri_Wayland

Reputation: 35

You are trying to instantiate a local variable out of it method. You need to put "gun1" before the constructor, and then use "gun1 = gun.getImage()" at the constructor.

Upvotes: 0

QuakeCore
QuakeCore

Reputation: 1926

Since all the previous answers didnt mention that java.awt.Image is actually an abstract class that cannot be instantiated, well i had to interfere! the is the best way to create an Image.

BufferedImage img = null;
try {
    img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
}

oh yah not to mention that gun1 object isnt defined in drawGun(Graphics2D g) method...

Upvotes: 4

ControlAltDel
ControlAltDel

Reputation: 35011

To load an Image, you can use java.awt.Toolkit.getImage(...), or (often the better option) javax.imageio.ImageIO's read methods

Upvotes: 0

user489041
user489041

Reputation: 28294

Use a class that extends Image such as BufferedImage . This has to do with basic OOP.

Upvotes: 0

Related Questions