I'm developing in BlueJ a simple game, it's like a "Space invaders". My problem is that, when I move an object, like the UFOs with a KeyListener
, the old UFOs don't disappear!
To update the frame I do:
public static void updateJframe()
{
SwingUtilities.updateComponentTreeUI(canvas);
}
canvas
is my variable from my class Canvas
that extends JFrame
.
If more code is needed I have no problem to post it.
Ok sorry for post the code in the comments, I'm a noob here too :$
public class Inout
{
private static Canvas canvas;
private Motor motor;
public Inout()
{
motor = new Motor(); //in class "Motor" is the logic of the game
canvas = new Canvas();
}
public static void actualizar() //this is the method where i'm trying to update the frame
{
canvas.removeAll();
SwingUtilities.updateComponentTreeUI(canvas);
}
public class Canvas extends JFrame implements KeyListener
{
public Canvas ()
{
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
setTitle("Space Invaders");
setSize(1200,600);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
int i = 0;
int j = 0;
for (i = 0; i < 30 ; i++)
{
for (j = 0; j < 50; j++)
{
if (Motor.cuadricula[i][j].esUfo())
{
g.setColor (Color.blue);
g.fillRect(i*40,j*20,20,15);
}
else if (Motor.cuadricula[i][j].esDef())
{
g.setColor (Color.red);
g.fillRect(i*40,j*20,20,15);}
}
}
}
}
public void keyPressed(KeyEvent e)
{}
public void keyReleased(KeyEvent e)
{
int keyCode = e.getKeyCode();
if(keyCode == KeyEvent.VK_P){
Motor.moverDef(1);//mover una casilla a la derecha
}
else if(keyCode == KeyEvent.VK_O){
Motor.moverDef(0);//mover una casilla a la izquierda
Inout.actualizar();
}
}
public void keyTyped (KeyEvent e){}
}
}
The topic that i can't understand is: if I use the "actualizar);" method from any other method it works fine, but if do it from the KeyListener the bug appear.
Many thanks for your help!!