Reputation: 591
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
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
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
I want to move all the drawing functions to my Engine class. I have this method in my Engine:
Upvotes: 1