我嘗試通過創建一個圓來測試我的圖形程序,然後在它們上添加關鍵字偵聽器並使它們工作。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");
}
}
關於:「那麼,你能改正我的代碼嗎?」 - 如果您遵循我們的建議並自行更正您的代碼*,那對您來說會更好。我建議你Google,並使用鍵綁定,而不是KeyListener。你可以很容易地找到一個體面的教程,以及在這個論壇中找到的許多例子(我寫的幾個例子)。運氣。 **編輯:**這是教程鏈接:[如何使用鍵綁定](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html) – 2011-12-27 17:07:54