0

I am trying to animate a circle in Java. I want it to move every time I press a key, but it is not working. Is there a problem with the way I am drawing the circle? Am I forgetting a repaint() somewhere.

import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel implements KeyListener {

    int x = 300, y = 300;

    public Main() {
        super();
    }

    public void paintComponent(Graphics g) {
        g.drawOval(x, y, 300, 300);
    }



    @Override
    public void keyPressed(KeyEvent e) {
        x++;
        y++;
        repaint();
    }

    @Override
    public void keyTyped(KeyEvent e) {}

    @Override
    public void keyReleased(KeyEvent e) {}

    public static void main(String[] args) {

        JFrame f = new JFrame();
        f.setSize(1200, 800);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setResizable(false);
        f.add(new Main());
        f.setVisible(true);

    }

}
Arnav Garg
  • 87
  • 9

2 Answers2

1

Don't use KeyListener, honestly, make use of the Key Bindings API instead, which has been designed to resolve the issues which KeyListener creates.

paintComponent in JPanel does an important job, you are expected to call it's super method before doing any custom painting.

See Painting in AWT and Swing and Performing Custom Painting for more details

You should also make an effort to initialise you UI from within the context of the Event Dispatching Thread, this solves a number of known issues on some platforms, see Initial Threads for more details

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You are not very far off. First, you need to actually add a listener for your key events.

f.addKeyListener(new KeyAdapter() {

    @Override
        public void keyPressed(KeyEvent e) {
            m.keyPressed(e);            
        }

});

Second, you'll notice this uses 'm'. That is a reference to your Main object.

Change:

f.add(new Main());

to:

Main m = new Main();

f.add(m);

Now it should work!

Chris
  • 694
  • 3
  • 18