Java游戏在战斗中冻结

时间:2013-02-22 21:10:12

标签: java swing paint freeze paintcomponent

我只是编写一个java游戏,我想做的是当我按空格时,角色进入战斗模式5秒然后释放它。我已经完成了,我按了一次,战斗模式启用,当我按下另一次时,它被释放,但当我尝试这样(底部的代码)游戏只是冻结了5秒但没有任何反应,我不喜欢甚至得到错误代码。

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;

public class Zeichnen extends JPanel {

    int x = 10;
    int y = 335;
    int width = 100;
    int height = 106;
    int speed = 10;
    boolean left = false;
    boolean fight = false;
    String file = "res/character.png";
    Image character;

    public void paint(Graphics g) {
        super.paintComponent(g);
        character = Toolkit.getDefaultToolkit().getImage(file);
        g.drawImage(character, x, y, width, height, this);
    }

    public void moveLeft() {
        if (left == false) {
            left = true;
            if (fight == true) {
                x = x + 129;
                width = -129;
            } else if (fight == false) {
                x = x + 100;
                width = -100;
            }
        }
        x = x - speed;
        rand();
        repaint();
    }

    public void moveRight() {
        if (left == true) {
            left = false;
            if (fight == true) {
                x = x - 129;
                width = 129;
            } else if (fight == false) {
                x = x - 100;
                width = 100;
            }
        }
        x = x + speed;
        rand();
        repaint();
    }

    public void moveUp() {
        y = y - speed;
        repaint();
    }

    public void moveDown() {
        y = y + speed;
        repaint();
    }

    public void fight() {
        long curTime = System.currentTimeMillis();
        fight = true;
        file = "res/character_fight.png";
        if (left == true) {
            width = -129;
        } else if (left == false) {
            width = 129;
        }
        repaint();
        if (System.currentTimeMillis() > curTime + 5000) {
            fight = false;
            file = "res/character.png";
            if (left == true) {
                width = -100;
            } else if (left == false) {
                width = 100;
            }
            repaint();
        }
    }

    public void rand() {
        if (x <= -130) {
            x = 770;
        } else if (x >= 770) {
            x = -130;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

应该遵守paint链机制,您应该覆盖paintComponent而不是paint。绘画时也不要加载图像,在初始化JPanel时加载它们。

答案 1 :(得分:0)

我不明白你的问题,你想要在按键时,你的角色形象会改变5秒钟吗?在这种情况下,您应该实现一个侦听器,然后打开一个计时器来安排计时器任务

TimerTask task = new TimerTask()  {
        @Override
        public void run() {
            //reset your character to normal state
            }
        }
};
new Timer().schedule(task, 5000);