Joe*_*asy 4 java applet keylistener
我完全不知道为什么我的程序没有识别键盘输入.我在整个程序中放置了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);
}
}
Run Code Online (Sandbox Code Playgroud)
当applet可聚焦并具有焦点时,可以检测到关键事件.管理焦点一直是applet的问题.问题主要在于Sun从不打算指定应该理想地应用于可聚焦HTML元素和applet的混合页面的焦点行为.
根据汤姆的建议,添加到最后 init()
setFocusable(true);
Run Code Online (Sandbox Code Playgroud)
为了安全起见,还要覆盖:
public void start() {
this.requestFocusInWindow();
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,通常最好在Swing中使用键绑定.他们还要求applet具有输入焦点.