2016-05-05 40 views
0

私は年末の学校プロジェクトのためにゲームを作っています。私のゲームでは、矢印キーを使って画面上でプレイヤーを移動できる必要があります。 私の矢印キーでイメージ(playerUpImageLabel)を移動したいのですが、どうすればよいかわかりません。私はこれを行う方法についてオンラインで調べてみるが、運はない。JAVA-矢印キーで画像を移動する

プログラムは今のところ動作しますが、矢印キーで画像(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); 

    } 

} 
+0

参照:http://stackoverflow.com/questions/36894487/java-gui-how-to-move-a-ball-using-wasd-keys/36894544#36894544 – camickr

答えて

0

Key Bindingsを使用してください。基本的には、具体的なKeyStrokeが呼び出されるたびに呼び出されるActionを作成する必要があります。

チェックアウトMotion Using The Keyboard作業例について。さらに、Key BindingsActionsを説明するSwingチュートリアルへのリンクがあります。

関連する問題