apllet 在使用 KeyListener 时 的问题 难道是Applet不是用KeyListener做键盘事件?
下面的代码 是从书上抄下来的 我只是把它改成了Applet 键盘就不响应 了
如果把它当成Applcation运行就能响应。
难道是Applet不是用KeyListener做键盘事件?
等待高人指点
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyboardEventDemo extends JApplet {
private KeyboardPanel keyboardPanel = new KeyboardPanel();
/** Initialize UI */
public KeyboardEventDemo() {
// Add the keyboard panel to accept and display user input
add(keyboardPanel);
// Set focus
keyboardPanel.setFocusable(true);
}
/** Main method */
public static void main(String[] args) {
JFrame f=new JFrame();
KeyboardEventDemo aa = new KeyboardEventDemo();
// frame.setTitle( "KeyboardEventDemo ");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(aa);
f.setSize(300, 300);
f.setVisible(true);
}
}
// KeyboardPanel for receiving key input
class KeyboardPanel extends JPanel implements KeyListener {
private int x = 100;
private int y = 100;
private char keyChar = 'A '; // Default key
public KeyboardPanel() {
addKeyListener(this); // Register listener
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN: y += 10; break;
case KeyEvent.VK_UP: y -= 10; break;
case KeyEvent.VK_LEFT: x -= 10; break;
case KeyEvent.VK_RIGHT: x += 10; break;
default: keyChar = e.getKeyChar();
}
System.out.println(keyChar);
repaint();
}
/** Draw the character */
protected void paintComponent(Graphics g) {
super.paintComponent(g);
System.out.println( "isFocusable : "+this.isFocusable());
g.setFont(new Font( "TimesRoman ", Font.PLAIN, 24));