2

我在 BlueJ 中开发一个简单的游戏,它就像一个“太空侵略者”。我的问题是,当我移动一个物体时,比如带有 的不明飞行物KeyListener,旧的不明飞行物不会消失!

要更新我做的框架:

public static void updateJframe()
{
  SwingUtilities.updateComponentTreeUI(canvas);
}

canvas是我的类Canvas中扩展的变量JFrame

如果需要更多代码,我可以毫无问题地发布它。

好的,抱歉在评论中发布代码,我也是菜鸟:$

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){}
    }
}

我无法理解的主题是:如果我使用“actualizar);” 任何其他方法中的方法都可以正常工作,但是如果从 KeyListener 中执行,则会出现错误。

非常感谢您的帮助!!

4

1 回答 1

1

好方法:使用paintComponent方法而不是paint,你不会遇到旧对象不消失@repaint的问题。

坏方法:每次调用paint时填充背景(在方法开始时) - 它会覆盖您之前绘制的所有内容。

于 2012-05-05T15:50:29.123 回答