当我点击按钮时,无法弄清楚如何摆脱图形

时间:2013-08-31 03:50:57

标签: java graphics paintcomponent shapes

我试图这样做当你按下按钮时,你会摧毁一些东西,但是我不能让敌人消失(红色方块)这是图形的代码:

public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            Ellipse2D P1 = (new Ellipse2D.Double(x, y, 40, 40));
            Rectangle2D P2 = (new Rectangle2D.Double(x2, y2, 40, 40));
            g2.fill(P1);
            g2.setPaint(Color.RED);
            g2.fill(P2);
        }

如何使用这种键绑定方法让Rectangle2D消失?

public void actionPerformed(ActionEvent e) {
            repaint();
            x += velx;
            y += vely;
            x2 += velx2;
            y2 += vely2;
        }
        public void up() {
            vely = -2;
            velx = 0;       
        }
        public void down() {
            vely = 2;
            velx = 0;       
        }
        public void left() {
            vely = 0;
            velx = -2;      
        }
        public void right() {
            vely = 0;
            velx = 2;       
        }
        public void stop() {
            vely = 0;
            velx = 0;       
        }
        public void stop2() {
            vely2 = 0;
            velx2 = 0;      
        }
        public void up2() {
            vely2 = -2;
            velx2 = 0;      
        }
        public void down2() {
            vely2 = 2;
            velx2 = 0;      
        }
        public void left2() {
            vely2 = 0;
            velx2 = -2;     
        }
        public void right2() {
            vely2 = 0;
            velx2 = 2;      
        }
        public void attack() {
            if (x <= x2+100 && y <= y2+100){

            }
        }
        //public void attack() {
        //  
        //}
        public void keyPressed(KeyEvent e) {
            int code = e.getKeyCode();
            if(code == KeyEvent.VK_UP){
                up();
            }
            if(code == KeyEvent.VK_DOWN){
                down();
            }
            if(code == KeyEvent.VK_LEFT){
                left();
            }
            if(code == KeyEvent.VK_RIGHT){
                right();
            }
            if(code == KeyEvent.VK_W){
                up2();
            }
            if(code == KeyEvent.VK_S){
                down2();
            }
            if(code == KeyEvent.VK_A){
                left2();
            }
            if(code == KeyEvent.VK_D){
                right2();
            }
            if(code == KeyEvent.VK_P){
                stop();
            }
            if(code == KeyEvent.VK_O){
                stop2();
            }
            if(code == KeyEvent.VK_Z){
                attack();
            }

        }

1 个答案:

答案 0 :(得分:0)

不是在paintComponent方法本身内创建要绘制的对象,而是维护要呈现的对象集合,并在每次paintComponent调用时遍历该集合。然后通过简单地从集合中删除来“销毁”P2对象。