VK_DOWN& VK_UP无法正常工作

时间:2015-09-12 16:16:45

标签: java swing jpanel keylistener paintcomponent

我正在尝试制作一个JAVA程序,当你打开它时,会弹出一个圆圈,你可以移动它。到目前为止,这是我的代码。

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.security.Key;

import javax.swing.JPanel;
import javax.swing.Timer;


public class WalkerCC extends JPanel implements ActionListener,     KeyListener{

Timer t = new Timer(5, this);
double x = 0, y = 0, velx = 0, vely = 0;

public WalkerCC() {
    t.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);

}

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.fill(new Ellipse2D.Double(x, 7, 40, 40));
}

public void actionPerformed(ActionEvent e) {
    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 e) {
    int code = e.getKeyCode();
    if (code == KeyEvent.VK_UP) {
        up();
    }

    if (code == KeyEvent.VK_DOWN) {
        down();
    }

    if (code == KeyEvent.VK_RIGHT) {
        right();
    }

    if (code == KeyEvent.VK_LEFT) {
        left();
    }

}
public void keyTyped(KeyEvent e) {}


public void keyReleased(KeyEvent e) {}

}

问题是,如果我打开应用程序并单击向左箭头,它会向左移动,而右键也是如此。但是,一旦我做了上下,它停止移动和doesent工作!

1 个答案:

答案 0 :(得分:4)

Error: Cannot find module 'htpasswd'
at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (/Users/MacUser/SailsProjects/SecurePanel/node_modules/http-auth/gensrc/auth/basic.js:11:14)

应该是:

g2.fill(new Ellipse2D.Double(x, 7, 40, 40));