I am making a game in java using the MVC design pattern (with swing) and I do not know how to make the Controller class separate from the view Class.
until now I have a model that contains all the data, a controller which in charge of all the logic and now I think about how to separate the view.
I have the GameView which extends the Jpanel and has a paintComonent:
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2D = (Graphics2D) g;
draw(g2D);
}
public void draw(Graphics2D g2D){
drawComponent(background, g2D);
drawComponent(arenaController.getArena().getPlane(), g2D);
drawComponent(arenaController.getArena().getPlayer().getBoat(), g2D);
ArrayList<PlaneDrop> planeDrops = arenaController.getArena().getPlaneDrops();
for(PlaneDrop planeDrop : planeDrops){
drawComponent(planeDrop, g2D);
}
g2D.drawString("Life: " + arenaController.getArena().getPlayer().getLife(), 10, 30);
g2D.drawString("Score: " + arenaController.getArena().getPlayer().getScore(), GAME_WIDTH - 50, 30);
}
but on the other hand, I have the GameEngine which in charge of the configuration and run
@Override
public void run() {
arenaController.init();
long waitTime = 0;
Graphics g = this.getGraphics();
gameViewer.paintComponent(g);
while(arenaController.isRunning()){
long startTime = System.currentTimeMillis();
gameViewer.paintComponent(g);
update(); // update game
gameViewer.repaint();
long endTime = System.currentTimeMillis() - startTime;
waitTime = (MILLISECOND / FPS) - endTime / MILLISECOND;
try{
Thread.sleep(waitTime);
} catch (Exception e){}
}
}
the run() method in the engine invokes the paintComponent() method of the view (which for me sounds like the controller --> invokes the viewer) but I find it is not the best way to do that and it is not recommended to invoke the paintComponent() directly.
So I want a clear separation of the controller and the view but I having trouble finding the appropriate way to do that.