How to pass more than one parameter in a Paint() method in Java?

Asked

Viewed 194 times

1

I was developing a project where I need to overwrite the Paint() method, but the Paint() method only receives a Graphics object as a parameter. What I need to do is create a Paint method that takes two parameters and uses Image objects belonging to the Other object to draw on the screen, for example`

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;

public class Desenho extends JPanel{

       public void paint(Graphics g, Outro o){
           Graphics2D g2d = (Graphics2D)g;
           g2d.drawImage(o.getImagem(), o.getX(), o.getY(), null);
       }
}

after that I would need to call this method and pass the parameters.

Outro o2 = new Outro();
Graphics gh = new Graphics();     // Não posso criar um Graphics assim pois Graphics é classe    abstrata.
paint(gh, o2);

The problem is that I cannot create a Graphics object outside of the method and so I cannot create the method with more than one argument.

If anyone knows how to do that or has a different idea that comes to the same result and can help me, I’d appreciate it.

  • 2

    If you’re looking to overwrite paint(), and everything indicates that yes, can not, need to find another way.

  • That’s exactly it and I had the same problem with several methods that get 'Graphics' as argument.

  • It’s hard to understand what you’re doing, but you need to organize the class to work differently, and not need the paint() receives this parameter, that is, it needs to be available in the instance to take it in.

1 answer

0

One way around this issue is to make the Outro on a class property.

And when instantiating the class passes it on the constructor!

Follow an example:

public class Desenho  extends JFrame{

    private Outro o;

    public Desenho(Outro o) {
        this.o = o;
    }

    @Override
    public void paint(Graphics g) {
        // TODO Auto-generated method s
            Graphics2D g2d = (Graphics2D)g;
            g2d.drawImage(o.getImagem(), o.getX(), o.getY(), null);
        super.paint(g);
    }
}

I don’t know if this form meets the scope of your application, but it is a solution!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.