【问题标题】:JAVA- Moving an image with arrow keys [duplicate]JAVA-用箭头键移动图像[重复]
【发布时间】:2016-05-05 13:46:39
【问题描述】:

我正在为我的期末学校项目制作游戏,在我的游戏中,需要能够使用箭头键在屏幕上移动玩家。 我想用箭头键移动图像(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);

  }

}

【问题讨论】:

标签: java swing awt arrow-keys


【解决方案1】:

您应该使用Key Bindings。基本上,您需要创建一个 Action,每当调用特定的 KeyStroke 时都会调用它。

查看Motion Using The Keyboard 以获取工作示例。此外,您还可以找到解释 Key BindingsActions 的 Swing 教程的链接。

【讨论】: