java through the direction keys to control small ball movement games

  • 2021-11-24 01:47:46
  • OfStack

This article needs to realize the specific process of java controlling the ball movement through the direction keys for your reference, the specific contents are as follows

Requirements analysis:

The first one is to draw a small ball

Second, we should be able to control its movement by controlling the direction keys

Implementation of Part 1

1. Draw a large form first

public class BallMove extends JFrame

When developing Java applications, it is common to use JFrame to create large windows. Windows created with JFrame contain a title, a Minimize button, a Maximize button, and a Close button

You can use its methods by inheriting the JFrame class with the main class

2. Then use a class to inherit JPanel. If JFrame is a window, JPanel is equivalent to a drawing board. We can add different button text and other elements on it

class MyPanel extends JPanel

3. Then we can draw on the drawing board

int x = 10;
int y = 10;
    public void paint(Graphics g) {

Using the method of JPanel, paint can draw a small ball Graphics is equivalent to a brush. It has many methods, such as drawing a circle and drawing a rectangle. We draw a small ball with a radius of 20 pixels at a distance of 10 pixels from x axis and y axis

4. At this point, the ball has been drawn. We only need to call it in the main method.

First define an MyPanel object

MyPanel myPanel = null;
 myPanel = new MyPanel();// Panel 

Then add it add into the JFrame framework by using the constructor


Set the size of the frame


Setting of Close Button


Display settings


The source code is below, so that we can get a small ball, but it still won't move at this time

It doesn't matter. Let it move at once!

Implementation of Part 2

class MyPanel extends JPanel implements KeyListener

1. First of all, implement the KeyListener interface. KeyListener can capture the input of keyboard and return the input information

2. There is one method we must implement

public void keyPressed(KeyEvent e)

That is, when the button is pressed

3. Content in the method body

class MyPanel extends JPanel

This is easy to understand is to manipulate the x y coordinates of the ball to move

4. Don't forget to redraw

Equivalent to refreshing the page

class MyPanel extends JPanel

Good about this small game to share here for everyone, you can also give their small ball painted color, or speed up the speed can be, I hope everyone more than 3 even support oh

The source code is as follows, you can play 1 play first, then do, the process of learning programming may not be so fun, often boring, and even make people lose confidence, but please believe that you 1 can, every master is coming from the vegetable chicken, they are powerful just because of the long contact time. Encourage each other!

class MyPanel extends JPanel

Related articles: