0

In my simple program, the starting point of a ball is x=0, y=0. A timer is also set on and in each Timer action, x is increased by a, and y by b. Initial values of a and b are both 1. And that works: when running the program Moving1.java, the ball is going from up and left of frame to right and down.

However, I tried to add KeyEvents also so that I can change values of a and b in KeyEvents, but they are not working. For some reason, it seems like program is not going to any KeyEvent. How it can be fixed? Main KeyEvent is keyPressed but I have written b = 0 to each KeyEvent and it should take effect to direction of ball.

If someone can help me with that issue, I suppose I can add correct software pieces to keyPressed Event like:

public void keyPressed (KeyEvent e) {
    int KeyCode = e.getKeyCode();
    if (KeyCode == KeyEvent.VK_LEFT) {
        a = -1;
        b = 0;
    }
}

and so on.

But here is my code:

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

public class Moving1 extends JPanel implements KeyListener {
    int x, y;
    int a = 1, b = 1;
    Timer timer;


    public Moving1() {
        x = 0;
        y = 0;
        timer = new Timer(30, new TimerListener());
    }

    private class TimerListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            x += a; // add horizontal
            y += b; // add vertical
            repaint();
        }
    }

    public void keyPressed(KeyEvent e) {
        b = 0;
    }

    public void keyReleased(KeyEvent e) {
        b = 0;
    }

    public void keyTyped(KeyEvent e) {
        b = 0;
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.fillOval(x, y, 10, 10);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame("Moving1");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Moving1 m = new Moving1();
        f.add(m);
        f.setSize(500, 500);
        f.setVisible(true);
        m.timer.start();
    }
}
3
  • Did you addKeyListener somewhere? Commented May 17, 2017 at 12:00
  • Documentation: docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html Commented May 17, 2017 at 12:01
  • your Moving1 is now an instance of KeyListener, but you didn't tell any component that it's supposed to use a KeyListener... Commented May 17, 2017 at 12:02

1 Answer 1

1

You're not adding the KeyListener to anything, so it can't handle any events. Put the following line in your main and that should get the events coming.

f.addKeyListener(m);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.