KeyListener不起作用

时间:2011-12-27 17:00:18

标签: java swing keylistener

我尝试通过创建一个圆圈来测试我的图形程序,然后在它们上面添加关键监听器并让它们工作。

但我看到它不起作用!但图形效果很好!

那么,你可以为我更正代码吗?

import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;

import javax.swing.*; //AWT extends

public class dotMoveByArrow extends JPanel implements ActionListener, KeyListener {

    Timer t = new Timer(5, (ActionListener) this);
    double x = 0, y = 0, velX = 2, velY= 2;

    public void dotMoveByArrow() {

        t.start();
        addKeyListener(this);
        setFocusable(true);
        setFocusTraversalKeysEnabled(false);
        setVisible(true);
    }

    public void paintComponent(Graphics g) {

        super.paintComponents(g);
        Graphics2D g2 = (Graphics2D) g;
        Ellipse2D circle = new Ellipse2D.Double(x, y, 40, 40);
        g2.fill(circle);
    }

    public void actionPerformed(ActionEvent event) {

        repaint();
        x += velX;
        y += velY;
    }

    public void up() {

        velY = -1.5;
        velX = 0;
    }

    public void down() {

        velY = 1.5;
        velX = 0;
    }

    public void left() {

        velX = -1.5;
        velY = 0;
    }

    public void right() {

        velX = 1.5;
        velY = 0;
    }

    public void keyPressed(KeyEvent event) {

        int key = event.getKeyCode();
        if (key == KeyEvent.VK_UP) {

            up();
            System.out.println("up");
        }

        if (key == KeyEvent.VK_DOWN) {

            down();
            System.out.println("down");
        }

        if (key == KeyEvent.VK_LEFT) {

            left();
            System.out.println("left");
        }

        if (key == KeyEvent.VK_RIGHT) {

            right();
            System.out.println("right");
        }
    }

    public void keyReleased(KeyEvent arg0) {}

    public void keyTyped(KeyEvent arg0) {}

    public static void main(String[] args) {

        dotMoveByArrow d = new dotMoveByArrow();
        JFrame f = new JFrame();

        f.getContentPane().add(d);
        f.setBackground(new Color(255, 255, 255));
        f.setUndecorated(true);
        f.setVisible(true);
        f.setSize(640, 480);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setTitle("Dot Move by Arrow");
    }
}

2 个答案:

答案 0 :(得分:3)

您的代码的一个问题是您已经定义了一个方法

public void dotMoveByArrow() { ... }

可能被认为是构造函数

public dotMoveByArrow() { ... }

(请注意声明中没有void

在您的代码中永远不会调用该方法,因此根本不会注册该侦听器。

答案 1 :(得分:3)

永远不会调用dotMoveByArrow方法,因此永远不会添加您的侦听器。如果dotMoveByArraow应该是构造函数,那么它应该声明为

public dotMoveByArrow()

没有void返回类型。按照惯例,Java类总是以大写字母开头。因此,构造函数也以大写字母开头。