我完全不知道为什么我的程序无法识别键盘输入。我在整个程序中放置了print语句来确定问题,并且我已经确定keyPressed方法永远不会激活。这是我为一个课程项目制作的游戏,是的,我是一个相对初学的程序员。提前致谢! (以下代码)
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.ImageIcon;
import javax.swing.JApplet;
public class Dodger extends JApplet implements Runnable, KeyListener {
Thread myThread;
public Image bg;
public Image pic;
public boolean loaded;
public int cx, cy, speed, x, y;
public void init(){
setSize(800,800);
loaded = false;
x = 2;
y = 400;
cx = 0;
cy = 0;
speed = 3;
myThread = new Thread(this);
myThread.start();
addKeyListener(this);
}
public void run(){
loadpic();
repaint();
while (myThread!=null)
{
try{
myThread.sleep(18);
}catch(InterruptedException e){
e.printStackTrace();
}
repaint();
}
}
public void upMotion(){
cy = cy + speed;
}
public void downMotion(){
cy = cy - speed;
}
public void leftMotion(){
cx = cx - speed;
}
public void rightMotion(){
cx = cx + speed;
}
@Override
public void keyPressed(KeyEvent k) {
if (k.getKeyCode() == KeyEvent.VK_LEFT) {
System.out.println("work");
leftMotion();
}
if (k.getKeyCode() == KeyEvent.VK_RIGHT) {
rightMotion();
}
if (k.getKeyCode() == KeyEvent.VK_UP) {
upMotion();
}
if (k.getKeyCode() == KeyEvent.VK_DOWN) {
downMotion();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
public void loadpic(){
bg = new ImageIcon(getClass().getResource("back.png")).getImage();
pic = new ImageIcon(getClass().getResource("smile.png")).getImage();
loaded = true;
repaint();
}
public void paint(Graphics g){
g.drawImage(bg, 0, 0, this);
g.drawImage(pic, cx, cy, this);
}
}
答案 0 :(得分:5)
当小程序可调焦时,可以检测到关键事件。有重点。管理焦点一直是applet的问题。问题主要在于Sun从不打算指定应该理想地应用于可聚焦HTML元素和applet的混合页面的焦点行为。
根据汤姆的建议,添加到init()
setFocusable(true);
为安全起见,也要覆盖:
public void start() {
this.requestFocusInWindow();
}
顺便说一句,通常最好在Swing中使用key bindings。他们还要求applet具有输入焦点。
答案 1 :(得分:3)
首先,您可能希望将您的类与KeyListener分开,因为它使得它更难阅读。
接下来,你想摆脱裸Thread
并将它包装在计时器中。
import javax.swing.Timer;
class Dodger extends JApplet {
Timer imageUpdater; //replaces Thread
/*...*/
public void init() {
/*etc*/
loadpic();
int repaintInterval = 100;
imageUpdater = new Timer(repaintInterval,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
}
}
);
imageUpdater.start();
addKeyListener(new KeyHandler());
setFocusable(true);
}
/*...*/
private class KeyHandler extends KeyAdapter {
/* Note that with this implementation, you do not have to override
* unnecessary methods, as KeyAdapter is an abstract class that
* implements all of the methods of KeyListener.
*/
@Override
public void keyPressed(KeyEvent e) {
/*...*/
}
}
/*...*/
}
大多数情况只是代码清理 - 实际问题可以通过setFocusable(true)
修复(根据Tom,见评论)。
答案 2 :(得分:1)
我不确定它是否适用于Applet,但您的Thread
可能不允许发生事件调度。
尝试使用SwingWorker运行“工作”。