Java keylisteners不做任何事情,但程序仍然运行

时间:2013-03-31 21:01:02

标签: java swing jframe keylistener

keylisteners应该上下移动块,但是当按下或按住键(w,s)时它们什么都不做。 这是代码(我省略了与问题无关的其他类)

感谢您的时间

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))
            {
            }
        }
    }
}

1 个答案:

答案 0 :(得分:5)