How to make an image move while listening to a keypress in Java
Question:
I'm learning Java programming and I want to create a game where an image moves left and right while a key is pressed. I can already draw an image and listen to a keypress, but how do I make the image move back and forth within the window while the window listens for a keypress? For example, if I press the space key, a laser should fire from the bottom of the screen.
Answer:
Yes, it's possible to make an image move back and forth within a window while listening for a keypress using a Swing Timer and Key Bindings. Here's an example:
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>In this example, the AnimationPanel class extends JPanel and handles the drawing and animation. The setupKeyBinding() method sets up the key bindings for arrow keys, and the MyKeyAction class handles the key press events and moves the image accordingly.</p><p>By using a combination of key bindings and a Swing Timer, you can make objects move back and forth within a window while listening for keypresses.</p>
The above is the detailed content of How to Make an Image Move in Java Based on Keypresses?. For more information, please follow other related articles on the PHP Chinese website!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

Dreamweaver Mac version
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

Zend Studio 13.0.1
Powerful PHP integrated development environment
