I am creating a pong game. I have fininshed the ball and paddle classes, the animator and everything else related. However when I open my created program only 1 paddle shows, while the other paddle and the ball do not show. If I change the way I draw things, the ball will show and the other 2 paddles don't. So it only draws 1 thing, whatever comes first. Here is the code for part which paints to the buffer.
public void renderlojen(){ // render game function
if(pamja==null){
pamja=createImage(GJERESIA,LARTESIA); // Image - serves as buffer
}
g =(Graphics2D) pamja.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, GJERESIA, LARTESIA);
doreza1.vizatodorezen(g); // paddle1
doreza2.vizatodorezen(g); // paddle2
topi1.vizatotopin(g); // ball
g.dispose();
}
public void updatolojen(){ // update game function
topi1.leviztopin();
doreza1.levizdorezen();
doreza2.levizdorezen();
}
public void pikturolojen(){ // draw from buffer to screen
if (pamja!=null){
g=(Graphics2D)this.getGraphics();
g.drawImage(pamja, 0, 0, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
System.out.println(doreza1.merrX());
System.out.println(doreza2.merrX());
}
else
System.out.println("Ska pamje");
}
public void vizatotopin(Graphics2D g2d){ // draw the ball code
topiforma =new Ellipse2D.Float(pozicioniX,pozicioniY,2*rrezja,2*rrezja);
g2d.setColor(Color.CYAN);
g2d.fill(topiforma);
g2d.dispose();
}
public void vizatodorezen (Graphics2D g2d){ // draw paddle code
drejtkendeshforma = new Rectangle2D.Float(pozicioniX,pozicioniY,GJERESIA,LARTESIA);
g2d.setColor(ngjyra);
g2d.fill(drejtkendeshforma);
g2d.dispose();
}
The problem is calling Graphics.dispose()
in the rendering methods of the game objects. Drawing to the Graphics
is not valid after that, so only the first object gets drawn.
In general, call Graphics.dispose()
only in the same method where you created it. Not in methods that receive one as a parameter.