Apcragg
Apcragg

Reputation: 133

Java keylisteners don't do anything but the program still runs

The keylisteners are supposed to move the block up and down but when the keys (w, s) are pressed or held they do nothing. Here is the code (I'm omitting the other class which has nothing to do with the problem)

Thank you for your time

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

public class Test extends JFrame
{
    private static final long serialVersionUID = 1L;
    JFrame f = new JFrame();

    public void Draw()
    {
        Handler handle = new Handler();
        f.addKeyListener(handle);
        f.setFocusable(true);
        f.requestFocusInWindow();
    }

    public static void main(String[] args)
    {
        JFrame f = new JFrame();
        f.setSize(400, 250);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    class Handler extends JFrame implements KeyListener
    {
        private static final long serialVersionUID = 1L;

        public void keyTyped(KeyEvent e)
        {
        }

        @Override
        public void keyPressed(KeyEvent e)
        {
            if ((e.getKeyCode() == KeyEvent.VK_S))
            {
                System.out.println("testw");
            }
            if ((e.getKeyCode() == KeyEvent.VK_W))
            {
            }

        }

        @Override
        public void keyReleased(KeyEvent e)
        {
            if ((e.getKeyCode() == KeyEvent.VK_UP))
            {
            }
            if ((e.getKeyCode() == KeyEvent.VK_DOWN))
            {
            }
        }
    }
}

Upvotes: 0

Views: 141

Answers (1)

mKorbel
mKorbel

Reputation: 109823

Upvotes: 5

Related Questions