ホームページ >Java >&#&チュートリアル >Javaでキー押下に基づいて画像を動かす方法?

Javaでキー押下に基づいて画像を動かす方法?

Patricia Arquette
Patricia Arquetteオリジナル
2024-12-01 01:19:12594ブラウズ

How to Make an Image Move in Java Based on Keypresses?

Java でキー押下を聞きながら画像を動かす方法

質問:

Java を学習していますプログラミングをしていて、キーを押している間画像が左右に動くゲームを作りたいと思っています。イメージを描画してキー入力をリッスンすることはすでにできていますが、ウィンドウがキー入力をリッスンしている間、ウィンドウ内でイメージを前後に移動させるにはどうすればよいでしょうか?たとえば、スペース キーを押すと、画面の下からレーザーが発射されるはずです。

答え:

はい、画像を動かすことができます。スイング タイマーとキー バインドを使用してキー押下をリッスンしながら、ウィンドウ内を行ったり来たりします。以下に例を示します。

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

public class AnimationWithKeyBinding {
   private static void createAndShowUI() {
      AnimationPanel panel = new AnimationPanel(); // the drawing JPanel

      JFrame frame = new JFrame("Animation With Key Binding");
      frame.getContentPane().add(panel);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      java.awt.EventQueue.invokeLater(new Runnable() {
         public void run() {
            createAndShowUI();
         }
      });
   }
}

@SuppressWarnings("serial")
class AnimationPanel extends JPanel {
   public static final int SPRITE_WIDTH = 20;
   public static final int PANEL_WIDTH = 400;
   public static final int PANEL_HEIGHT = 400;
   private static final int MAX_MSTATE = 25;
   private static final int SPIN_TIMER_PERIOD = 16;
   private static final int SPRITE_STEP = 3;

   private int mState = 0;
   private int mX = (PANEL_WIDTH - SPRITE_WIDTH) / 2;
   private int mY = (PANEL_HEIGHT - SPRITE_WIDTH) / 2;
   private int oldMX = mX;
   private int oldMY = mY;
   private boolean moved = false;

   // an array of sprite images that are drawn sequentially
   private BufferedImage[] spriteImages = new BufferedImage[MAX_MSTATE];

   public AnimationPanel() {
      // create and start the main animation timer
      new Timer(SPIN_TIMER_PERIOD, new SpinTimerListener()).start();
      setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
      setBackground(Color.white);
      createSprites(); // create the images
      setupKeyBinding();
   }

   private void setupKeyBinding() {
      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inMap = getInputMap(condition);
      ActionMap actMap = getActionMap();

      // this uses an enum of Direction that holds ints for the arrow keys
      for (Direction direction : Direction.values()) {
         int key = direction.getKey();
         String name = direction.name();

         // add the key bindings for arrow key and shift-arrow key
         inMap.put(KeyStroke.getKeyStroke(key, 0), name);
         inMap.put(KeyStroke.getKeyStroke(key, InputEvent.SHIFT_DOWN_MASK), name);
         actMap.put(name, new MyKeyAction(this, direction));
      }
   }

   // create a bunch of buffered images and place into an array,
   // to be displayed sequentially
   private void createSprites() {
      for (int i = 0; i <p>この例では、AnimationPanel クラスは JPanel を拡張し、描画とアニメーションを処理します。 setupKeyBinding() メソッドは矢印キーのキー バインドを設定し、MyKeyAction クラスはキー押下イベントを処理し、それに応じて画像を移動します。</p><p>キー バインドと Swing Timer の組み合わせを使用すると、次のことができます。オブジェクトはキー押下をリッスンしながらウィンドウ内を前後に移動します。</p>

以上がJavaでキー押下に基づいて画像を動かす方法?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。