使用带有线程的KeyListener来操作图像

时间:2017-10-30 19:23:12

标签: java jpanel actionlistener keylistener java-threads

我正在尝试创建一个步行动画。它应该在playerLeft和playerLeftWalk之间交替。代码如下所示:

public class MyClass extends JPanel implements ActionListener, KeyListener{
    protected Timer tm = new Timer(10, this);
    protected Clip clip;
    protected Image background, playerSprite, playerLeft, playerLeftWalk;
    protected int mapdx = 0;
    protected int mapdy = 0;
    protected int mapX = 0;
    protected int mapY = 0;
    protected int playerX = 1060;
    protected int playerY = 2800;
    protected volatile boolean activeThread;

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(this.background, this.mapX + this.mapdx, this.mapY - this.mapdy, this);
        g.drawImage(this.playerSprite, this.playerX, this.playerY, this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        mapX += mapdx;
        mapY += mapdy;
        this.repaint();             
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int k = e.getKeyCode();

        Thread playerControl=null;
        if (!activeThread) {
            this.activeThread=true;
            playerControl = new Thread(new Runnable() {
                @Override
                public void run() {
                    switch (k) {
                    case KeyEvent.VK_LEFT:
                        mapdx = 1;
                        mapdy = 0;
                        System.out.println("Map X: " + mapX + " Map Y: " + mapY);
                        try {
                            playerSprite = playerLeftWalk;
                            Thread.sleep(250);
                            playerSprite = playerLeft;
                        } catch (InterruptedException e) {
                        }
                        break;

                    default:
                        break;
                    }
                }
            });
            activeThread=false;
        }   
        if(playerControl!=null)
            playerControl.start();
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int k = e.getKeyCode();
        if(k == KeyEvent.VK_LEFT) {
            mapdx = 0;
            mapdy = 0;
            playerSprite = playerLeft;
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }
}

以上代码的作用是为第一个"循环"然后口吃。我假设正在发生的事情是正在创建多个线程,使图像口吃。

0 个答案:

没有答案