JAVA-用箭头键移动图像

时间:2016-05-05 13:46:40

标签: java swing awt arrow-keys

我正在为我的年终学校项目制作游戏,并且在我的游戏中,需要能够使用箭头键在屏幕上移动玩家。 我想用我的箭头键移动图像(playerUpImageLabel),但我不知道如何。我试着在网上看看如何做到这一点,但没有运气。

该程序截至目前已有效,但我不知道如何使用箭头键移动图像(playerUpImageLabel)。

请帮助吗?

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Game {

  public void game() {

     JFrame gameFrame = new JFrame();
     JPanel gamePanel = new JPanel();
     JLabel floorLabel = new JLabel();
     JLabel copyrightLabel = new JLabel();

     ImageIcon floorImage = new ImageIcon();

     int playerMovementX;
     int playerMovementY;

     playerMovementX = 280;
     playerMovementY = 280;

     ImageIcon playerUpImage = new ImageIcon();
     JLabel playerUpImageLabel = new JLabel();

     ImageIcon playerLeftImage = new ImageIcon();
     JLabel playerLeftImageLabel = new JLabel();

     ImageIcon playerRightImage = new ImageIcon();
     JLabel playerRightImageLabel = new JLabel();

     ImageIcon playerDownImage = new ImageIcon();
     JLabel playerDownImageLabel = new JLabel();


     ImageIcon playerNormalImage = new ImageIcon();
     JLabel playerNormalImageLabel = new JLabel();

     gameFrame = new JFrame("Zombehs");
     gameFrame.setVisible(true);
     gameFrame.setSize(600, 620);
     gameFrame.setResizable(false);
     gameFrame.setLocationRelativeTo(null);
     gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


     gamePanel = new JPanel();
     gamePanel.setLayout(null);
     gameFrame.add(gamePanel);


     floorImage = new ImageIcon(getClass().getResource("/Users/JakeBorg/Desktop/JavaPro/res/floor.png"));
     floorLabel = new JLabel(floorImage);
     floorLabel.setBounds(0, 0, 600, 600);


     copyrightLabel = new JLabel("Copyright @ 2016 Jake_Borg");
     copyrightLabel.setFont(new Font("DorFont01", Font.BOLD, 10));
     copyrightLabel.setBounds(500, 580, 100, 10);


     // Player
     playerUpImage = new ImageIcon(getClass().getResource("/Users/JakeBorg/Desktop/JavaPro/res/player/Up_1.png"));
     playerUpImageLabel = new JLabel(playerUpImage);
     playerUpImageLabel.setBounds(playerMovementX, playerMovementY, 33,  33);

     playerNormalImageLabel = playerUpImageLabel;



     gamePanel.add(playerNormalImageLabel);
     gamePanel.add(floorLabel);
     gamePanel.add(copyrightLabel);

  }

}

1 个答案:

答案 0 :(得分:0)

您应该使用Key Bindings。基本上,您需要创建一个Action,只要调用特定的KeyStroke,就会调用该Key Bindings

查看Motion Using The Keyboard的工作示例。此外,您还可以找到指向Actionsbreak

的Swing教程的链接
相关问题