import java.awt.event.KeyEvent;
import java.awt.event.KeyListener; import javax.swing.JFrame;/* * To change this template, choose Tools | Templates * and open the template in the editor. */import javax.swing.JPanel;import javax.swing.JTextField;/** * * @author 李效伦 */public class HOHO extends JFrame implements KeyListener{ private JTextField t; private boolean left = false; private boolean right = false; private boolean up = false; private boolean down = false; public HOHO() { JPanel p = new JPanel(); this.add(p); p.setLayout(null); t = new JTextField(); t.setEditable(false); p.add(t); t.setSize(100,30); t.setLocation(200,200); this.setFocusable(true); this.addKeyListener(this); this.setSize(480,480); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { int i = e.getKeyCode(); switch(i) { case KeyEvent.VK_LEFT : left=true; break; case KeyEvent.VK_UP : up= true;break; case KeyEvent.VK_DOWN :down = true; break; case KeyEvent.VK_RIGHT : right = true;break; } if(up==false&&down==false&&left==false&&right==false) { t.setText("什么也没按"); } else if(up==true&&down==false&&left==false&&right==false) { t.setText("上"); } else if(up==false&&down==true&left==false&&right==false) { t.setText("下"); } else if(up==false&&down==true&left==true&&right==false) { t.setText("左下"); } else if(up==true&&down==false&left==false&&right==true) { t.setText("右上"); } else if(up==true&&down==false&left==true&&right==false) { t.setText("左上"); } else if(up==false&&down==true&left==false&&right==true) { t.setText("右下"); } else if(up==false&&down==false&left==true&&right==false) { t.setText("左"); } else if(up==false&&down==false&left==false&&right==true) { t.setText("右"); } } public void keyReleased(KeyEvent e) { int i = e.getKeyCode(); switch(i) { case KeyEvent.VK_LEFT : left=false; break; case KeyEvent.VK_UP : up= false;break; case KeyEvent.VK_DOWN :down = false; break; case KeyEvent.VK_RIGHT : right = false;break; } } public static void main(String[] args){ new HOHO(); } }