user2444217
user2444217

Reputation: 591

Java Drawing Graphics

I am making a game in Java and I have a canvas class, which has the game tick, and I draw the images on the canvas using

public void paint(Graphics g) {
    // draw stuff here
}

I want to move all the drawing functions to my Engine class. I have this method in my Engine:

@Override
public void render(Graphics scene) {
 // draw stuff here
}

In my Canvas I didn't have to call the paint method, but in the Engine I would have to call the render method, but since it takes as an argument Graphics scene, I am kind of at a loss. How would I be able to draw components from my Engine class(using the render method) and not from the Canvas class.

The engine class does not extend any JComponent, but it does initialize the Canvas object

Upvotes: 1

Views: 266

Answers (2)

chessbot
chessbot

Reputation: 436

One problem is that there is no way for Engine to know that paint(g) is called, since the call is run on the canvas. So you will most likely need to modify Canvas.paint so that it calls the Engine. It's possible there is some funky listener you could add to Canvas but I think that's probably more complicated than you need.

One way that would work would be to pass an instance of Engine to the Canvas on construction:

public class Engine {
    private Canvas canvas;
    public Engine() {
        Canvas = new Canvas(this);
    }
    public void render(Graphics g) {
        // do stuff
    }
}

public class Canvas extends JPanel {
    private Engine engine;
    public Canvas(Engine engine) {
         this.engine = engine;
    }
    @Override
    public void paintComponent(Graphics g) {
          super.paintComponent(g);
          engine.render(g);
    }
}

Upvotes: 0

mKorbel
mKorbel

Reputation: 109813

I am making a game in Java and I have a canvas class, which has the game tick, and I draw the images on the canvas using

note

public void paint(Graphics g) { for awt.Canvas, awt.Panel

public void paintComponent(Graphics g) { for swing.JComponent, swing.JPanel

  • any painting could be done only for J/Component, good practicies couldn't be move this methods outside of J/Component declarations

I want to move all the drawing functions to my Engine class. I have this method in my Engine:

  • is good idea to prepare all Object before paint/paintComponent is executed,
  • there to put all Objects to the array
  • inside paint/paintComponent only loop inside arrays of prepared Obects, invoked from Swing Timer, Mouse/Key events
  • all events for paiting, to AWT/Swing GUI must be done on Event Dispatch Thread
  • for todays GUI to use Swing JComponent, JPanel and override paintComponent
  • a few very good code examples are here, tagged by paintComponent

Upvotes: 1

Related Questions