Mastering Java Swing
Moving A Ball With Arrow Keys
Keyboard and Mouse InteractionHere we make an interactive animation. You can use the arrow keys to control the position of the ball, moving it up, down, left, or right.
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Main extends JPanel implements KeyListener {
private int x = 150; // Ball's initial X position
private int y = 150; // Ball's initial Y position
public Main() {
JFrame frame = new JFrame("Move the Ball with Arrow Keys");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.add(this);
frame.addKeyListener(this); // Listen for key presses
frame.setVisible(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); // Clear the panel
g.setColor(Color.GREEN); // Set ball color
g.fillOval(x, y, 50, 50); // Draw the ball at the current position
}
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode(); // Get the key that was pressed
if (key == KeyEvent.VK_UP) { // Move up
y -= 10;
} else if (key == KeyEvent.VK_DOWN) { // Move down
y += 10;
} else if (key == KeyEvent.VK_LEFT) { // Move left
x -= 10;
} else if (key == KeyEvent.VK_RIGHT) { // Move right
x += 10;
}
repaint(); // Update the screen with the new position
}
@Override
public void keyReleased(KeyEvent e) { }
@Override
public void keyTyped(KeyEvent e) { }
public static void main(String[] args) {
new Main();
}
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 27 more lessons in Mastering Java Swing.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.