标签:
按键事件可以利用键盘来控制和执行一些动作,或者从键盘上获取输入,只要按下,释放一个键或者在一个组件上敲击,就会触发按键事件。KeyEvent对象描述事件的特性(按下,放开,或者敲击一个键)和对应的值。java提供KeyListener接口处理按键事件。
1 import java.awt.*; 2 import java.awt.event.*; 3 import javax.swing.*; 4 5 public class KeyEventDemo extends JFrame{ 6 private KeyboardPanel keyboardPanel = new KeyboardPanel(); 7 8 public KeyEventDemo(){ 9 add( keyboardPanel); 10 11 keyboardPanel.setFocusable(true); 12 13 } 14 15 public static void main(String[] args){ 16 KeyEventDemo frame = new KeyEventDemo(); 17 frame.setTitle( "KeyEventDemo"); 18 frame.setSize(300,300); 19 frame.setLocationRelativeTo( null); 20 frame.setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE); 21 frame.setVisible( true); 22 23 } 24 25 static class KeyboardPanel extends JPanel{ 26 private int x = 100; 27 private int y = 100; 28 private char KeyChar = ‘A‘ ; 29 30 public KeyboardPanel(){ 31 addKeyListener( new KeyAdapter(){ 32 public void keyPressed(KeyEvent e){ 33 switch(e.getKeyCode()){ 34 case KeyEvent.VK_DOWN: y += 10;break; 35 case KeyEvent.VK_UP: y -= 10; break; 36 case keyEvent.VK_LEFT: x -= 10; break; 37 case KeyEvent.VK_RIGHT: x += 10; break; 38 default: keyChar = e.getKeyChar(); 39 } 40 41 repaint(); 42 } 43 }); 44 } 45 46 protected void paintComponent(Graphics g){ 47 super.paintComponent(g); 48 49 g.setFont( new Font("TimesRoman" ,Font.PLAIN,24)); 50 g.drawString(String. valueOf(KeyChar), x, y); 51 } 52 } 53 }
标签:
原文地址:http://www.cnblogs.com/fnlingnzb-learner/p/5954277.html