javaswingkeyboardkeyeventkey-events

How to get keyEvent to work in Java?


I'm completely new at programming Java. I can't get my keyEvents to wont work. I need this for a little game I'm making. Here is my code:

package markusrytter.pingpong;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
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 {

    static int ballX;
    static int ballY;
    static int ballR = 15;

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.fillOval(ballX - ballR, ballY - ballR, ballR * 2, ballR * 2);
    }
    public static void main(String[] args) throws InterruptedException {
        JFrame frame = new JFrame("Sample Frame");
        main game = new main();
        frame.add(game);
        frame.setSize(1400, 800);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);

        ballX = frame.getContentPane().getSize().width / 2;
        ballY = frame.getContentPane().getSize().height / 2;

        while (true) {
            game.repaint();
            Thread.sleep(10);
        }
    }

    public void keyPressed(KeyEvent e) {
        System.out.println("A key is Pressed: " + e.getKeyCode());
        if(e.getKeyCode() == KeyEvent.VK_SPACE){
            System.out.println("Spacebutton pressed");
        }
    }
}

I do hope someone can help, I have tried to watch videos but again, I'm new at java.


Solution

  • Most importantly: change the name of your class. It's called main and that's a bad idea. Also it's much more advisable to override paintComponent() instead of paint.

    You didn't add the keylistener to the JFrame. You should call this in your main after creating game:

    frame.addKeyListener(game);
    

    You also need to add the remaining KeyListener methods.

    and that should do it.