package chapter16;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
@SuppressWarnings("serial")
public class KeyEventDemo extends JFrame{
aa one = new aa();
public KeyEventDemo (){
add(one);
one.setFocusable(true);
}
public static void main(String[] args) {
KeyEventDemo frame = new KeyEventDemo();
frame.setTitle("KeyEventDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
static class aa extends JPanel{
private int x = 50;
private int y = 50;
private char keychar = 'A';
public aa(){
addKeyListener(new KeyAdapter() {
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();
}
repaint();
}
});
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.setFont(new Font("TimesRoman",Font.PLAIN,24));
g.drawString(String.valueOf(keychar), x, y);
}
}
}
点击键盘上的字母,输出在屏幕上,如果不是字母,不显示
另外 按方向键,可以控制字母的左右上下方向移动