-1

i'm just programming a java game and what i want to do is that when i press space, the character goes into fight mode for 5 sec and then release it. i already have done, that i press one time, fight mode gets enabled and when i press another time, its getting released but when i try it like this (code at bottom) the game just freezes for 5 sec but nothing happens and i don't even get a error code.

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;
        }
    }
}
4

2 回答 2

1

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

于 2013-02-22T21:14:14.877 回答
0

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

TimerTask task = new TimerTask()  {
        @Override
        public void run() {
            //reset your character to normal state
            }
        }
};
new Timer().schedule(task, 5000);
于 2013-02-22T21:27:51.363 回答