Mr beginner
Mr beginner

Reputation: 9

Adding KeyListener in Java?

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();
    }
}

Upvotes: 0

Views: 983

Answers (1)

Kayaman
Kayaman

Reputation: 73558

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);

Upvotes: 1

Related Questions