Как реализовать анимацию в JFrame?

Рейтинг: 0Ответов: 0Опубликовано: 10.06.2023

Мне нужно добавить анимацию в JFrame при нажатии клавиши, а именно смену спрайтов персонажа. Я сделал это с помощью KeyListener, но во время обработки команды изображение не меняется. Как решить эту проблему?

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.concurrent.TimeUnit;
import javax.swing.*;

public class help {

    public static JLabel player = new JLabel();

    public static ImageIcon player_1 = new ImageIcon("C:\\Users\\SaigaScarAS\\Desktop\\game\\player1.png");
    public static ImageIcon player_2 = new ImageIcon("C:\\Users\\SaigaScarAS\\Desktop\\game\\player2.png");
    public static ImageIcon player_3 = new ImageIcon("C:\\Users\\SaigaScarAS\\Desktop\\game\\player3.png");
    public static ImageIcon player_4 = new ImageIcon("C:\\Users\\SaigaScarAS\\Desktop\\game\\player4.png");
    public static ImageIcon player_5 = new ImageIcon("C:\\Users\\SaigaScarAS\\Desktop\\game\\player5.png");

    public static TimeUnit t = TimeUnit.MILLISECONDS;
    public static int T = 100;

    public static void main(String[] args) {

        JFrame map = new JFrame();
        map.setExtendedState(JFrame.MAXIMIZED_BOTH);
        map.setUndecorated(true);
        map.setLayout(null);

        player.setIcon(player_1);
        player.setBounds(400,200,200,200);
        player.setVisible(true);
        map.add(player);

        map.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                int keyCode = e.getKeyCode();
                if (keyCode == KeyEvent.VK_SPACE) {
                    player.setIcon(player_2);
                    try {
                        t.sleep(T);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    player.setIcon(player_3);
                    try {
                        t.sleep(T);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    player.setIcon(player_4);
                    try {
                        t.sleep(T);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    player.setIcon(player_5);
                    try {
                        t.sleep(T);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                    player.setIcon(player_1);
                }
            }
        });
        map.setVisible(true);
    }
}

Ответы

Ответов пока нет.