Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Recently, I'm making a simple engine using raw java and its default libraries. I want to make simple constructor methods to draw images using paintComponent();, but I encounter an error and don't really know how to fix it to make it work properly.

Here is the problem: I made a class called Texture, then made its constructor in the class, like this:
Java
public Texture(String path, int scalex, int scaley) {
    
    ImageIcon tex3 = new ImageIcon(getClass().getResource(path));
    Image tex2 = tex3.getImage();
    Image tex1 = tex2.getScaledInstance(scalex, scaley, java.awt.Image.SCALE_REPLICATE);
    Image tex = tex1;
    
    
}

first, I instantiate a Texture:
Java
Texture player = new Texture("res/player.png", 1, 1);

Then, I try to draw it using g.drawImage(); like this:
Java
public void paintComponent(Graphics g) {
    
    super.paintComponent(g);
    g.drawImage(player, 100, 100, null);
    
}

But I encounter an error saying "The method drawImage(Image, int, int, ImageObserver) in the type Graphics is not applicable for the arguments (Texture, int, int, null)"

I really don't know how to fix this besides deleting the Texture constructor and just doing what the constructor does but in the class.

How can I make the Texture class usable for the Image class in the method g.drawImage()?

Thank you for anyone's help, I've been having trouble with this. It's probably an easy fix but mistakes make you learn!

~ Pale-Gray

What I have tried:

I've tried changing the constructor to "public Image Texture() {}" but that won't work,
I've tried casting it to an Image "Texture tex = (Image) new Texture();
Posted
Comments
Mohibur Rashid 14-Apr-21 20:15pm    
if this is the graphics class you are using
https://docs.oracle.com/javase/7/docs/api/java/awt/Graphics.html
then all the methods named drawImage only accept Image(link: https://docs.oracle.com/javase/7/docs/api/java/awt/Image.html). Image is an abstract class, you need to declare Texture by extending Image class.

And also, you need to learn java.
Pale-Gray 14-Apr-21 20:32pm    
I've extended the Texture class with the Image class, still doesn't work
Pale-Gray 14-Apr-21 21:09pm    
I made it work somehow, but not. Its giving out an IllegalArgumentException saying "Invalid Image Variant"
Mohibur Rashid 15-Apr-21 20:07pm    
Can you share your updated source codes?
Richard MacCutchan 15-Apr-21 3:52am    
You should pass the Image object to the drawImage method.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900